Ejemplo n.º 1
0
        public void GrantUserObjectAccess(ISiteSetting siteSetting, Guid objectId, string objectLogicalName, Guid userId, int accessrightmask)
        {
            IOrganizationService organizationService = GetClientContext(siteSetting);
            //no delete access
            GrantAccessRequest grant = new GrantAccessRequest();

            grant.Target = new EntityReference(objectLogicalName, objectId);

            PrincipalAccess principal = new PrincipalAccess();

            principal.Principal   = new EntityReference("systemuser", userId);
            principal.AccessMask  = AccessRights.ReadAccess | AccessRights.AppendAccess | AccessRights.WriteAccess | AccessRights.AppendToAccess | AccessRights.ShareAccess | AccessRights.AssignAccess;
            grant.PrincipalAccess = principal;

            try
            {
                GrantAccessResponse grant_response = (GrantAccessResponse)organizationService.Execute(grant);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            /*
             * Entity account = new Entity("principalobjectaccess");
             * account["objectid"] = objectId;
             * account["principalid"] = userId;
             * account["accessrightsmask"] = accessrightmask;
             * Guid _accountId = organizationService.Create(account);
             */
        }
Ejemplo n.º 2
0
        private GrantAccessResponse HandleGrantAccess(OrganizationRequest orgRequest, EntityReference userRef)
        {
            var request = MakeRequest <GrantAccessRequest>(orgRequest);
            var resp    = new GrantAccessResponse();

            dataMethods.GrantAccess(request.Target, request.PrincipalAccess, userRef);
            return(resp);
        }
        public async Task Remove_Two_UserAccessPermission_FromUserWithClientAccess_AndRegionAccess_SingleCost_Pass()
        {
            var grantAccessResponse = new GrantAccessResponse
            {
                UserGroup  = new UserGroup(),
                New        = true,
                UserGroups = new[] { Guid.NewGuid().ToString() }
            };

            var userBeingUpdated        = _users.First(user => user.Id == _UserWithTwoRolesId);
            var agencyOwnerBusinessRole = _businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner);
            var firstCost = _costs.First(a => a.CostNumber == "number1");

            var updateUserModel = new UpdateUserModel
            {
                AccessDetails = new List <AccessDetail>()
            };

            EfContext.AbstractType.AddRange(_abstractTypes);
            EfContext.Role.AddRange(_roles);
            EfContext.BusinessRole.AddRange(_businessRoles);
            EfContext.CostUser.AddRange(_users);
            EfContext.Cost.AddRange(_costs);
            EfContext.SaveChanges();

            _costStageRevisionServiceMock.Setup(a => a.GetStageDetails <PgStageDetailsForm>(It.IsAny <Guid>())).ReturnsAsync(_costStageReviDetailsFormFirstCost);
            _permissionServiceMock.Setup(a => a.CheckHasAccess(_xUserId, userBeingUpdated.Id, AclActionType.Edit, "user")).ReturnsAsync(true);
            _permissionServiceMock
            .Setup(a => a.GrantUserAccess <Cost>(agencyOwnerBusinessRole.RoleId, firstCost.Id, userBeingUpdated, BuType.Pg, null,
                                                 _costStageReviDetailsFormFirstCost.SmoName, It.IsAny <bool>()))
            .ReturnsAsync(grantAccessResponse);

            _permissionServiceMock.Setup(a => a.RevokeAccessForSubjectWithRole(It.IsAny <Guid>(), It.IsAny <Guid>(), It.IsAny <Guid>(), null, It.IsAny <bool>()))
            .ReturnsAsync(new[] { Guid.NewGuid().ToString() });

            // Act
            var result = await _pgUserService.UpdateUser(User, userBeingUpdated.Id, updateUserModel, BuType.Pg);

            // Assert
            result.Messages.First().Should().Be("User updated.");
            result.Success.Should().Be(true);

            _permissionServiceMock.Verify(a =>
                                          a.RevokeAccessForSubjectWithRole(It.IsAny <Guid>(), _UserWithTwoRolesId,
                                                                           It.IsAny <Guid>(), null, It.IsAny <bool>()), Times.Exactly(2));

            _permissionServiceMock.Verify(
                a => a.GrantUserAccess <Cost>(agencyOwnerBusinessRole.RoleId, firstCost.Id, userBeingUpdated, BuType.Pg, null,
                                              _costStageReviDetailsFormFirstCost.BudgetRegion.Name, It.IsAny <bool>()),
                Times.Never);
        }
Ejemplo n.º 4
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            #region "Load CRM Service from context"

            Common objCommon = new Common(executionContext);
            objCommon.tracingService.Trace("Load CRM Service from context --- OK");
            #endregion

            #region "Read Parameters"
            String _SharingRecordURL = this.SharingRecordURL.Get(executionContext);
            if (_SharingRecordURL == null || _SharingRecordURL == "")
            {
                return;
            }
            string[] urlParts       = _SharingRecordURL.Split("?".ToArray());
            string[] urlParams      = urlParts[1].Split("&".ToCharArray());
            string   objectTypeCode = urlParams[0].Replace("etc=", "");
            string   objectId       = urlParams[1].Replace("id=", "");
            objCommon.tracingService.Trace("ObjectTypeCode=" + objectTypeCode + "--ParentId=" + objectId);

            EntityReference teamReference = this.Team.Get(executionContext);
            principals.Clear();

            if (teamReference != null)
            {
                principals.Add(teamReference);
            }

            #endregion

            #region "ApplyRoutingRuteamReferenceleRequest Execution"
            string EntityName = objCommon.sGetEntityNameFromCode(objectTypeCode, objCommon.service);

            EntityReference refObject = new EntityReference(EntityName, new Guid(objectId));

            objCommon.tracingService.Trace("Grant Request--- Start");

            GrantAccessRequest grantRequest = new GrantAccessRequest();
            grantRequest.Target                     = refObject;
            grantRequest.PrincipalAccess            = new PrincipalAccess();
            grantRequest.PrincipalAccess.AccessMask = (AccessRights)getMask(executionContext);
            foreach (EntityReference principalObject2 in principals)
            {
                grantRequest.PrincipalAccess.Principal = principalObject2;
                GrantAccessResponse grantResponse = (GrantAccessResponse)objCommon.service.Execute(grantRequest);
            }

            objCommon.tracingService.Trace("Grant Request--- end");

            #endregion
        }
Ejemplo n.º 5
0
        public void GrantAccess(EntityReference Record, EntityReference Principal, AccessRights AccessRights)
        {
            PrincipalAccess principalAccess = new PrincipalAccess();

            principalAccess.Principal  = Principal;
            principalAccess.AccessMask = AccessRights;

            GrantAccessRequest grantAccessRequest = new GrantAccessRequest();

            grantAccessRequest.Target          = Record;
            grantAccessRequest.PrincipalAccess = principalAccess;

            GrantAccessResponse grantAccessResponse = (GrantAccessResponse)OrganizationService.Execute(grantAccessRequest);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Grants a specific user Read Access to a specific Entity record.
        /// </summary>
        /// <param name="OrganizationService"></param>
        /// <param name="Record">EntityReference of the record.</param>
        /// <param name="UserId">GUID of user that is getting access.</param>
        public void GrantUserReadAccess(EntityReference Record, Guid UserId)
        {
            PrincipalAccess principalAccess = new PrincipalAccess();

            principalAccess.Principal  = new EntityReference("systemuser", UserId);
            principalAccess.AccessMask = AccessRights.ReadAccess;

            GrantAccessRequest grantAccessRequest = new GrantAccessRequest();

            grantAccessRequest.Target          = Record;
            grantAccessRequest.PrincipalAccess = principalAccess;

            GrantAccessResponse grantAccessResponse = (GrantAccessResponse)OrganizationService.Execute(grantAccessRequest);
        }
        //Share function
        private void ShareRecord(Guid userId, Entity task, IOrganizationService service, CodeActivityContext activityContext)
        {
            GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                Target          = new EntityReference(task.LogicalName, task.Id),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal  = new EntityReference("systemuser", userId),
                    AccessMask = (AccessRights)getMask(activityContext)
                }
            };

            // Execute the request.
            GrantAccessResponse grantResponse =
                (GrantAccessResponse)service.Execute(grantRequest);
        }
Ejemplo n.º 8
0
        //Share function
        private void ShareRecordasReadOnly(Guid Userid, Entity task, IOrganizationService service)
        {
            GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                Target          = new EntityReference(task.LogicalName, task.Id),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal  = new EntityReference("systemuser", Userid),
                    AccessMask = AccessRights.ReadAccess
                }
            };

            // Execute the request.
            GrantAccessResponse grantResponse =
                (GrantAccessResponse)service.Execute(grantRequest);
        }
Ejemplo n.º 9
0
        //Share function
        private void ShareRecord(Guid teamId, Entity workOrder, IOrganizationService service, CodeActivityContext activityContext)
        {
            GrantAccessRequest grantRequest = new GrantAccessRequest()
            {
                Target          = new EntityReference(workOrder.LogicalName, workOrder.Id),
                PrincipalAccess = new PrincipalAccess()
                {
                    Principal  = new EntityReference("team", teamId),
                    AccessMask = (AccessRights)getMask(activityContext)
                }
            };

            // Execute the request.
            GrantAccessResponse grantResponse =
                (GrantAccessResponse)service.Execute(grantRequest);
        }
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            GrantAccessResponse response = new GrantAccessResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("TemporaryCredential", targetDepth))
                {
                    var unmarshaller = TemporaryCredentialUnmarshaller.Instance;
                    response.TemporaryCredential = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return(response);
        }
        /// <summary>
        /// Demonstrates sharing records by exercising various access messages including:
        /// Grant, Modify, Revoke, RetrievePrincipalAccess, and
        /// RetrievePrincipalsAndAccess.
        /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    _service = (IOrganizationService)_serviceProxy;

                    CreateRequiredRecords();

                    #region GrantAccess Message

                    // Create the request object and set the target and principal access
                    // object.
                    GrantAccessRequest grantRequest = new GrantAccessRequest()
                    {
                        Target          = new EntityReference(Account.EntityLogicalName, _accountId),
                        PrincipalAccess = new PrincipalAccess()
                        {
                            Principal  = new EntityReference(SystemUser.EntityLogicalName, _userId),
                            AccessMask = AccessRights.WriteAccess | AccessRights.ReadAccess | AccessRights.ShareAccess
                        }
                    };

                    // Execute the request.
                    GrantAccessResponse grantResponse =
                        (GrantAccessResponse)_service.Execute(grantRequest);

                    Console.Write("Access Granted ");

                    #endregion

                    #region ModifyAccess Message

                    // Create the request object and set the target and principal access
                    // object.
                    ModifyAccessRequest modifyRequest = new ModifyAccessRequest()
                    {
                        Target          = new EntityReference(Account.EntityLogicalName, _accountId),
                        PrincipalAccess = new PrincipalAccess()
                        {
                            Principal  = new EntityReference(SystemUser.EntityLogicalName, _userId),
                            AccessMask = AccessRights.ReadAccess | AccessRights.ShareAccess
                        }
                    };

                    // Execute the request.
                    ModifyAccessResponse modifyResponse =
                        (ModifyAccessResponse)_service.Execute(modifyRequest);

                    Console.Write("and Modified. ");

                    #endregion

                    #region RetrievePrincipalAccess Message

                    // Create the request object and set the target and principal.
                    RetrievePrincipalAccessRequest retrieveRequest = new RetrievePrincipalAccessRequest()
                    {
                        Target    = new EntityReference(Account.EntityLogicalName, _accountId),
                        Principal = new EntityReference(SystemUser.EntityLogicalName, _userId)
                    };

                    // Execute the request.
                    RetrievePrincipalAccessResponse retrieveResponse =
                        (RetrievePrincipalAccessResponse)_service.Execute(retrieveRequest);

                    Console.Write("Retrieved principal access. ");

                    #endregion

                    #region RetrieveSharedPrincipalsAndAccess Message

                    // Create the request object and set the target.
                    RetrieveSharedPrincipalsAndAccessRequest retrieveSharedRequest =
                        new RetrieveSharedPrincipalsAndAccessRequest()
                    {
                        Target = new EntityReference(Account.EntityLogicalName, _accountId)
                    };

                    // Execute the request.
                    RetrieveSharedPrincipalsAndAccessResponse retrieveSharedResponse =
                        (RetrieveSharedPrincipalsAndAccessResponse)_service.Execute(retrieveSharedRequest);

                    Console.Write("Retrieved principals and access. ");

                    #endregion

                    #region RevokeAccess Message

                    // Create the request object and set the target and revokee.
                    RevokeAccessRequest revokeRequest = new RevokeAccessRequest()
                    {
                        Target  = new EntityReference(Account.EntityLogicalName, _accountId),
                        Revokee = new EntityReference(SystemUser.EntityLogicalName, _userId)
                    };

                    // Execute the request.
                    RevokeAccessResponse revokeResponse =
                        (RevokeAccessResponse)_service.Execute(revokeRequest);

                    Console.Write("Revoked Access.");

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        public async Task Add_SingleUserAccessPermission_ToRegion_ForSingleCost_Pass()
        {
            var grantAccessResponse = new GrantAccessResponse
            {
                UserGroup  = new UserGroup(),
                New        = true,
                UserGroups = new[] { Guid.NewGuid().ToString() }
            };

            var updateUserModel = new UpdateUserModel
            {
                AccessDetails = new List <AccessDetail>
                {
                    new AccessDetail
                    {
                        ObjectType     = core.Constants.AccessObjectType.Region,
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyOwner).Id,
                        LabelName      = "RegionOne"
                    }
                }
            };

            EfContext.AbstractType.AddRange(_abstractTypes);
            EfContext.Role.AddRange(_roles);
            EfContext.BusinessRole.AddRange(_businessRoles);
            EfContext.CostUser.AddRange(_users);
            EfContext.Cost.AddRange(_costs);
            EfContext.SaveChanges();

            var userBeingUpdated        = _users.First(user => user.Id == _userNoRoles);
            var agencyOwnerBusinessRole = _businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner);
            var firstCost = _costs.First(a => a.CostNumber == "number1");

            _costStageRevisionServiceMock.Setup(a => a.GetStageDetails <PgStageDetailsForm>(It.IsAny <CostStageRevision>())).Returns(_costStageReviDetailsFormFirstCost);
            _permissionServiceMock.Setup(a => a.CheckHasAccess(_xUserId, userBeingUpdated.Id, AclActionType.Edit, "user")).ReturnsAsync(true);
            _permissionServiceMock
            .Setup(a => a.GrantUserAccess <Cost>(
                       agencyOwnerBusinessRole.RoleId, firstCost.Id, userBeingUpdated, BuType.Pg, null, _costStageReviDetailsFormFirstCost.SmoName, It.IsAny <bool>()))
            .ReturnsAsync(grantAccessResponse);

            // Act
            var result = await _pgUserService.UpdateUser(User, userBeingUpdated.Id, updateUserModel, BuType.Pg);

            // Assert
            result.Messages.First().Should().Be("User updated.");
            result.Success.Should().Be(true);

            var verifyUser = EfContext.CostUser.First(a => a.Id == userBeingUpdated.Id);

            verifyUser.UserBusinessRoles.Count.Should().Be(1);
            verifyUser.UserBusinessRoles.First().BusinessRole.Id.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Id);
            verifyUser.UserBusinessRoles.First().BusinessRole.Value.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Value);
            verifyUser.UserBusinessRoles.First().BusinessRole.Key.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Key);
            verifyUser.UserBusinessRoles.First().BusinessRole.Role.Id.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Role.Id);

            _permissionServiceMock.Verify(
                a => a.GrantUserAccess <Cost>(agencyOwnerBusinessRole.RoleId, firstCost.Id, userBeingUpdated, BuType.Pg, null,
                                              _costStageReviDetailsFormFirstCost.BudgetRegion.Name
                                              , It.IsAny <bool>()),
                Times.Once);
        }
        public async Task Add_TwoUserAccessPermission_OneRegion_OneGlobal_ForSingleCost_Pass()
        {
            var grantAccessResponse = new GrantAccessResponse
            {
                UserGroup  = new UserGroup(),
                New        = true,
                UserGroups = new[] { Guid.NewGuid().ToString() }
            };

            var updateUserModel = new UpdateUserModel
            {
                AccessDetails = new List <AccessDetail>
                {
                    new AccessDetail
                    {
                        ObjectId       = _abstractTypes.First(a => a.Type == core.Constants.AccessObjectType.Module).Id,
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyOwner).Id,
                        ObjectType     = core.Constants.AccessObjectType.Client
                    },
                    new AccessDetail
                    {
                        ObjectType     = core.Constants.AccessObjectType.Region,
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyFinanceManager).Id,
                        LabelName      = "RegionOne"
                    }
                }
            };

            EfContext.AbstractType.AddRange(_abstractTypes);
            EfContext.Role.AddRange(_roles);
            EfContext.BusinessRole.AddRange(_businessRoles);
            EfContext.CostUser.AddRange(_users);
            EfContext.Cost.AddRange(_costs);
            EfContext.SaveChanges();

            var userBeingUpdated        = _users.First(user => user.Id == _userNoRoles);
            var agencyOwnerBusinessRole = _businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner);
            var firstCost          = _costs.First(a => a.CostNumber == "number1");
            var agencyAbstractType = _abstractTypes.First(a => a.Type == core.Constants.AccessObjectType.Agency);

            _costStageRevisionServiceMock.Setup(a => a.GetStageDetails <PgStageDetailsForm>(It.IsAny <CostStageRevision>())).Returns(_costStageReviDetailsFormFirstCost);
            _permissionServiceMock.Setup(a => a.CheckHasAccess(_xUserId, userBeingUpdated.Id, AclActionType.Edit, "user")).ReturnsAsync(true);
            _permissionServiceMock
            .Setup(a => a.GrantUserAccess <Cost>(agencyOwnerBusinessRole.RoleId, firstCost.Id, userBeingUpdated, BuType.Pg, null,
                                                 _costStageReviDetailsFormFirstCost.SmoName, It.IsAny <bool>()))
            .ReturnsAsync(grantAccessResponse);

            _permissionServiceMock.Setup(a =>
                                         a.CreateDomainNode(typeof(AbstractType).Name.ToSnakeCase(), agencyAbstractType.Id, It.IsAny <Guid>(), It.IsAny <Guid>()))
            .ReturnsAsync(new[] { Guid.NewGuid().ToString() });

            _pgAgencyServiceMock.Setup(a =>
                                       a.GetOrCreatePseudoAgencies(It.IsAny <Agency[]>()))
            .ReturnsAsync(
                _abstractTypes
                .Where(at => at.Type == core.Constants.AccessObjectType.Agency)
                .Select(a => new AbstractType())
                .ToList()
                );

            // Act
            var result = await _pgUserService.UpdateUser(User, userBeingUpdated.Id, updateUserModel, BuType.Pg);

            // Assert
            result.Messages.First().Should().Be("User updated.");
            result.Success.Should().Be(true);

            var verifyUser = EfContext.CostUser.First(a => a.Id == userBeingUpdated.Id);

            verifyUser.UserBusinessRoles.Count.Should().Be(3);
            verifyUser.UserBusinessRoles.First().BusinessRole.Id.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Id);
            verifyUser.UserBusinessRoles.First().BusinessRole.Value.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Value);
            verifyUser.UserBusinessRoles.First().BusinessRole.Key.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Key);
            verifyUser.UserBusinessRoles.First().BusinessRole.Role.Id.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Role.Id);
            verifyUser.UserBusinessRoles.First().Labels.Length.Should().Be(0);

            verifyUser.UserBusinessRoles.Last().BusinessRole.Id.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyFinanceManager).Id);
            verifyUser.UserBusinessRoles.Last().BusinessRole.Value.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyFinanceManager).Value);
            verifyUser.UserBusinessRoles.Last().BusinessRole.Key.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyFinanceManager).Key);
            verifyUser.UserBusinessRoles.Last().BusinessRole.Role.Id.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyFinanceManager).Role.Id);
            verifyUser.UserBusinessRoles.Last().Labels.Length.Should().Be(1);
            verifyUser.UserBusinessRoles.Last().Labels.First().Should().Be("RegionOne");

            //Only one cost exists so only needed to be Add_ed
            _permissionServiceMock.Verify(
                a => a.GrantUserAccess <Cost>(agencyOwnerBusinessRole.RoleId, firstCost.Id, userBeingUpdated, BuType.Pg, null,
                                              _costStageReviDetailsFormFirstCost.BudgetRegion.Name, It.IsAny <bool>()),
                Times.Once);
        }
        public async Task Add_Two_UserAccessPermission_TwoDifferentRegions_singleBusinessRoleWithLabels_SingleCost_Pass()
        {
            var grantAccessResponse = new GrantAccessResponse
            {
                UserGroup  = new UserGroup(),
                New        = true,
                UserGroups = new[] { Guid.NewGuid().ToString() }
            };

            var userBeingUpdated = _users.First(user => user.Id == _userNoRoles);
            var firstCost        = _costs.First(a => a.CostNumber == "number1");
            var secondCost       = _costs.First(a => a.CostNumber == "number2");
            var thirdCost        = _costs.First(a => a.CostNumber == "number3");
            //Same Role is used here on purpose!
            //We are checking if the Business Role gains extra labels!
            var updateUserModel = new UpdateUserModel
            {
                AccessDetails = new List <AccessDetail>
                {
                    new AccessDetail
                    {
                        ObjectType     = core.Constants.AccessObjectType.Region,
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyFinanceManager).Id,
                        LabelName      = "RegionTwo"
                    },
                    new AccessDetail
                    {
                        ObjectType     = core.Constants.AccessObjectType.Region,
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyFinanceManager).Id,
                        LabelName      = "RegionOne"
                    }
                }
            };

            EfContext.AbstractType.AddRange(_abstractTypes);
            EfContext.Role.AddRange(_roles);
            EfContext.BusinessRole.AddRange(_businessRoles);
            EfContext.CostUser.AddRange(_users);
            EfContext.Cost.AddRange(_costs);
            EfContext.SaveChanges();

            _costStageRevisionServiceMock.Setup(a => a.GetStageDetails <PgStageDetailsForm>(firstCost.LatestCostStageRevision))
            .Returns(_costStageReviDetailsFormFirstCost);
            _costStageRevisionServiceMock.Setup(a => a.GetStageDetails <PgStageDetailsForm>(secondCost.LatestCostStageRevision))
            .Returns(_costStageReviDetailsFormSecondCost);
            _costStageRevisionServiceMock.Setup(a => a.GetStageDetails <PgStageDetailsForm>(thirdCost.LatestCostStageRevision))
            .Returns(_costStageReviDetailsFormThirdCost);

            _permissionServiceMock.Setup(a => a.CheckHasAccess(_xUserId, userBeingUpdated.Id, AclActionType.Edit, "user")).ReturnsAsync(true);
            _permissionServiceMock
            .Setup(a => a.GrantUserAccess <Cost>(It.IsAny <Guid>(), It.IsAny <Guid>(), userBeingUpdated, BuType.Pg, null,
                                                 It.IsAny <string>(), It.IsAny <bool>()))
            .ReturnsAsync(grantAccessResponse);

            _permissionServiceMock.Setup(a => a.RevokeAccessForSubjectWithRole(It.IsAny <Guid>(), It.IsAny <Guid>(), It.IsAny <Guid>(), null, It.IsAny <bool>()))
            .ReturnsAsync(new[] { Guid.NewGuid().ToString() });

            // Act
            var result = await _pgUserService.UpdateUser(User, userBeingUpdated.Id, updateUserModel, BuType.Pg);

            // Assert
            result.Messages.First().Should().Be("User updated.");
            result.Success.Should().Be(true);

            var verifyUser = EfContext.CostUser.First(a => a.Id == userBeingUpdated.Id);

            verifyUser.UserBusinessRoles.Count.Should().Be(1);
            verifyUser.UserBusinessRoles.First().Labels.Length.Should().Be(2);
            verifyUser.UserBusinessRoles.First().Labels.Any(a => a.Contains("RegionTwo")).Should().BeTrue();
            verifyUser.UserBusinessRoles.First().Labels.Any(a => a.Contains("RegionOne")).Should().BeTrue();

            _permissionServiceMock.Verify(
                a => a.GrantUserAccess <Cost>(It.IsAny <Guid>(), It.IsIn(firstCost.Id, secondCost.Id, thirdCost.Id), userBeingUpdated, BuType.Pg, null,
                                              It.IsIn(_costStageReviDetailsFormFirstCost.BudgetRegion.Name, _costStageReviDetailsFormSecondCost.BudgetRegion.Name,
                                                      _costStageReviDetailsFormThirdCost.BudgetRegion.Name), It.IsAny <bool>()),
                Times.Once);
        }
        public async Task Add_SingleUserAccessPermission_ToSmo_ForSingleCost_Pass()
        {
            var grantAccessResponse = new GrantAccessResponse
            {
                UserGroup  = new UserGroup(),
                New        = true,
                UserGroups = new[] { Guid.NewGuid().ToString() }
            };

            var clientModule = new Module
            {
                Id         = Guid.NewGuid(),
                ClientType = ClientType.Pg,
                Name       = "Procter & Gamble",
                ClientTag  = "costPG",
                Key        = "P&G"
            };
            var abstractTypes = new List <AbstractType>
            {
                new AbstractType
                {
                    Id       = Guid.NewGuid(),
                    ObjectId = clientModule.Id,
                    Module   = clientModule,
                    Type     = core.Constants.AccessObjectType.Module
                }
            };

            var updateUserModel = new UpdateUserModel
            {
                AccessDetails = new List <AccessDetail>
                {
                    new AccessDetail
                    {
                        ObjectType     = core.Constants.AccessObjectType.Smo,
                        BusinessRoleId = _businessRoles.First(a => a.Value == Constants.BusinessRole.AgencyOwner).Id,
                        LabelName      = "SmoName1"
                    }
                }
            };

            EfContext.AbstractType.AddRange(abstractTypes);
            EfContext.Role.AddRange(_roles);
            EfContext.BusinessRole.AddRange(_businessRoles);
            EfContext.CostUser.AddRange(_users);
            EfContext.Cost.AddRange(_costs);
            EfContext.SaveChanges();

            var userBeingUpdated        = _users.First(user => user.Id == _userNoRoles);
            var agencyOwnerBusinessRole = _businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner);
            var firstCost = _costs.First(a => a.CostNumber == "number1");

            _costStageRevisionServiceMock.Setup(a => a.GetStageDetails <PgStageDetailsForm>(It.IsAny <Guid>())).ReturnsAsync(_costStageReviDetailsFormFirstCost);
            _permissionServiceMock.Setup(a => a.CheckHasAccess(_xUserId, userBeingUpdated.Id, AclActionType.Edit, "user")).ReturnsAsync(true);
            _permissionServiceMock
            .Setup(a => a.GrantUserAccess <Cost>(agencyOwnerBusinessRole.RoleId, firstCost.Id, userBeingUpdated, BuType.Pg, null,
                                                 _costStageReviDetailsFormFirstCost.SmoName, It.IsAny <bool>()))
            .ReturnsAsync(grantAccessResponse);
            _aclClientMock.Setup(a => a.Access.CheckAccessToDomainNode(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(HttpStatusCode.OK);
            _aclClientMock.Setup(a => a.Get.GetObjectUserGroups(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(new AclResponseObject <List <ResponseRole> >
            {
                Status   = HttpStatusCode.OK,
                Response = new List <ResponseRole>
                {
                    new ResponseRole
                    {
                        ExternalId = Guid.NewGuid().ToString(),
                        Name       = Guid.NewGuid().ToString()
                    }
                }
            });

            _permissionServiceMock
            .Setup(a => a.GrantUserAccess <Cost>(
                       agencyOwnerBusinessRole.RoleId, firstCost.Id, userBeingUpdated, BuType.Pg, null, _costStageReviDetailsFormFirstCost.SmoName, It.IsAny <bool>()))
            .ReturnsAsync(grantAccessResponse);

            // Act
            var result = await _pgUserService.UpdateUser(User, userBeingUpdated.Id, updateUserModel, BuType.Pg);

            // Assert
            result.Messages.First().Should().Be("User updated.");
            result.Success.Should().Be(true);

            var verifyUser = EfContext.CostUser.First(a => a.Id == userBeingUpdated.Id);

            verifyUser.UserBusinessRoles.Count.Should().Be(1);
            verifyUser.UserBusinessRoles.First().BusinessRole.Id.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Id);
            verifyUser.UserBusinessRoles.First().BusinessRole.Value.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Value);
            verifyUser.UserBusinessRoles.First().BusinessRole.Key.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Key);
            verifyUser.UserBusinessRoles.First().BusinessRole.Role.Id.Should().Be(_businessRoles.First(br => br.Value == Constants.BusinessRole.AgencyOwner).Role.Id);

            _permissionServiceMock.Verify(
                a => a.GrantUserAccess <Cost>(
                    agencyOwnerBusinessRole.RoleId, firstCost.Id, userBeingUpdated, BuType.Pg, null, _costStageReviDetailsFormFirstCost.SmoName, It.IsAny <bool>()),
                Times.Once);
        }