public static async Task<AuthorizationTokenDO> CreateSalesforceAuthToken()
        {
            using (var uow = ObjectFactory.GetInstance<IUnitOfWork>())
            {
                var emailAddressId = uow.EmailAddressRepository.FindOne(e => e.Address.Equals("*****@*****.**")).Id;
                var userDO = uow.UserRepository.FindOne(u => u.EmailAddressID == emailAddressId);
                var terminalId = uow.TerminalRepository.FindOne(t => t.Name.Equals("terminalSalesforce")).Id;

                var tokenDTO = await terminalIntegrationTests.Fixtures.HealthMonitor_FixtureData.Salesforce_AuthToken();

                var tokenDO = new AuthorizationTokenDO()
                {
                    ExternalAccountId = tokenDTO.ExternalAccountId,
                    Token = tokenDTO.Token,
                    TerminalID = terminalId,
                    UserID = userDO.Id,
                    AdditionalAttributes = tokenDTO.AdditionalAttributes,
                };

                uow.AuthorizationTokenRepository.Add(tokenDO);
                uow.SaveChanges();

                return tokenDO;
            }
        }
Пример #2
0
        public static void AuthTokenRemoved(AuthorizationTokenDO authToken)
        {
            var handler = EventAuthTokenRemoved;

            if (handler != null)
            {
                handler.Invoke(authToken);
            }
        }
Пример #3
0
        public static void AuthTokenSilentRevoke(AuthorizationTokenDO authToken)
        {
            var handler = EventAuthTokenSilentRevoke;

            if (handler != null)
            {
                handler.Invoke(authToken);
            }
        }
        /*********************************************************************************/

        private void UpdateCache(AuthorizationTokenDO authorizationToken)
        {
            var cacheKey = GetCacheKey(authorizationToken.Id);

            TokenCache.Remove(cacheKey);
            TokenCache.Add(new CacheItem(cacheKey, authorizationToken.Clone()), new CacheItemPolicy
            {
                SlidingExpiration = Expiration
            });
        }
        private async Task ApplyAuthTokenToSolution(ActivityDTO solution, AuthorizationTokenDO salesforceAuthToken)
        {
            var applyToken = new AuthenticationTokenGrantDTO()
            {
                ActivityId  = solution.Id,
                AuthTokenId = salesforceAuthToken.Id,
                IsMain      = true
            };

            await HttpPostAsync <AuthenticationTokenGrantDTO[], string>(GetHubApiBaseUrl() + "authentication/tokens/grant", new[] { applyToken });
        }
        private string FormatTerminalName(AuthorizationTokenDO authorizationToken)
        {
            var terminal = _terminal.GetByKey(authorizationToken.TerminalID);

            if (terminal != null)
            {
                return(terminal.Label);
            }

            return(authorizationToken.TerminalID.ToString());
        }
        private async Task <Tuple <string, string> > CreateCase(AuthorizationTokenDO authToken)
        {
            var token   = Mapper.Map <AuthorizationToken>(authToken);
            var manager = _container.GetInstance <SalesforceManager>();
            var name    = Guid.NewGuid().ToString();
            var data    = new Dictionary <string, object> {
                { "SuppliedEmail", TestEmail }, { "SuppliedName", name }
            };

            return(new Tuple <string, string>(await manager.Create(SalesforceObjectType.Case, data, token), name));
        }
Пример #8
0
        public async Task <ExternalAuthUrlDTO> GetOAuthInitiationURL(
            Fr8AccountDO user,
            TerminalDO terminal)
        {
            if (terminal.AuthenticationType == AuthenticationType.None)
            {
                throw new WrongAuthenticationTypeException();
            }

            var restClient = ObjectFactory.GetInstance <IRestfulServiceClient>();

            var response = await restClient.PostAsync(
                new Uri(terminal.Endpoint + "/authentication/request_url"),
                null,
                _terminalService.GetRequestHeaders(terminal, user.Id));

            var externalAuthUrlDTO = JsonConvert.DeserializeObject <ExternalAuthUrlDTO>(response);

            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                var authToken = uow.AuthorizationTokenRepository
                                .GetPublicDataQuery()
                                .FirstOrDefault(x => x.TerminalID == terminal.Id &&
                                                x.UserID == user.Id &&
                                                x.ExternalAccountId == null &&
                                                x.ExternalStateToken != null
                                                );

                if (authToken == null)
                {
                    var curTerminal = _terminalService.GetByKey(terminal.Id);
                    var curAccount  = uow.UserRepository.GetByKey(user.Id);

                    authToken = new AuthorizationTokenDO
                    {
                        UserID             = curAccount.Id,
                        TerminalID         = curTerminal.Id,
                        ExternalStateToken = externalAuthUrlDTO.ExternalStateToken
                    };

                    uow.AuthorizationTokenRepository.Add(authToken);
                }
                else
                {
                    authToken.ExternalAccountId  = null;
                    authToken.Token              = null;
                    authToken.ExternalStateToken = externalAuthUrlDTO.ExternalStateToken;
                }

                uow.SaveChanges();
            }

            return(externalAuthUrlDTO);
        }
        private async Task CleanUp(AuthorizationTokenDO authTokenDO, Guid initialPlanId)
        {
            if (initialPlanId != Guid.Empty)
            {
                // await HttpDeleteAsync(_baseUrl + "Plans/Delete?id=" + initialPlanId.ToString());
            }

            if (authTokenDO != null)
            {
                await HttpPostAsync <string>(_baseUrl + "authentication/tokens/revoke?id=" + authTokenDO.Id.ToString(), null);
            }
        }
        private AuthorizationTokenDO NewToken(IUnitOfWork uow, Guid id, string securePart)
        {
            AuthorizationTokenDO token = new AuthorizationTokenDO
            {
                Id         = id,
                Token      = securePart,
                TerminalID = FixtureData.GetTestGuidById(1)
            };

            uow.AuthorizationTokenRepository.Add(token);

            return(token);
        }
        /*********************************************************************************/

        public void Add(AuthorizationTokenDO authorizationTokenDo)
        {
            AuthorizationTokenChangeTracker tracker;

            if (_changesTackers.TryGetValue(authorizationTokenDo.Id, out tracker))
            {
                if (!ReferenceEquals(tracker.ActualValue, authorizationTokenDo))
                {
                    throw new InvalidOperationException($"AuthorizationToken with Id = {authorizationTokenDo.Id} was already added");
                }

                return;
            }

            Track(authorizationTokenDo, EntityState.Added);
        }
Пример #12
0
        private async Task <Guid> CreatePlan_SaveAndGetDataFromSalesforce(AuthorizationTokenDO authToken)
        {
            //get required activity templates
            var activityTemplates = await HttpGetAsync <IEnumerable <ActivityTemplateCategoryDTO> >(_baseUrl + "activity_templates");

            var atSave = activityTemplates.Single(at => at.Name.Equals(ActivityCategories.Forward.Name)).Activities.Single(a => a.Name.Equals("Save_To_SalesforceDotCom"));
            var atGet  = activityTemplates.Single(at => at.Name.Equals(ActivityCategories.Receive.Name)).Activities.Single(a => a.Name.Equals("Get_Data"));

            Assert.IsNotNull(atSave, "Save to Salesforce.com activity is not available");
            Assert.IsNotNull(atGet, "Get Salesforce Data activity is not available");
            Debug.WriteLine("Got required activity templates.");

            //create initial plan
            var initialPlan = await HttpPostAsync <PlanNoChildrenDTO, PlanDTO>(_baseUrl + "plans", new PlanNoChildrenDTO()
            {
                Name = "SaveToAndGetFromSalesforce"
            });

            Debug.WriteLine("Created initial plan without actions");

            string mainUrl          = _baseUrl + "activities/create";
            var    postUrl          = "?activityTemplateId={0}&createPlan=false";
            var    formattedPostUrl = string.Format(postUrl, atSave.Id);

            formattedPostUrl += "&parentNodeId=" + initialPlan.StartingSubPlanId;
            formattedPostUrl += "&authorizationTokenId=" + authToken.Id.ToString();
            formattedPostUrl += "&order=" + 1;
            formattedPostUrl  = mainUrl + formattedPostUrl;
            var saveToSfActivity = await HttpPostAsync <ActivityDTO>(formattedPostUrl, null);

            Assert.IsNotNull(saveToSfActivity, "Initial Create and Configure of Save to Salesforce activity is failed.");
            Debug.WriteLine("Create and Initial Configure of Save to Salesforce activity is successful.");

            mainUrl           = _baseUrl + "activities/create";
            postUrl           = "?activityTemplateId={0}&createPlan=false";
            formattedPostUrl  = string.Format(postUrl, atGet.Id);
            formattedPostUrl += "&parentNodeId=" + initialPlan.StartingSubPlanId;
            formattedPostUrl += "&authorizationTokenId=" + authToken.Id.ToString();
            formattedPostUrl += "&order=" + 2;
            formattedPostUrl  = mainUrl + formattedPostUrl;
            var getDataActivity = await HttpPostAsync <ActivityDTO>(formattedPostUrl, null);

            Assert.IsNotNull(getDataActivity, "Initial Create and Configure of Get Data activity is failed.");
            Debug.WriteLine("Create and Initial Configure of Get Data activity is successful.");

            return(initialPlan.Id);
        }
Пример #13
0
 public static void AddAuthorizationToken(Fr8AccountDO user, string externalAccountId)
 {
     using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
     {
         var tokenDO = new AuthorizationTokenDO()
         {
             UserID     = user.Id,
             TerminalID = FixtureData.GetTestGuidById(1),
             AuthorizationTokenState = AuthorizationTokenState.Active,
             ExpiresAt         = null,
             Token             = @"{""Email"":""64684b41-bdfd-4121-8f81-c825a6a03582"",""ApiPassword"":""HyCXOBeGl/Ted9zcMqd7YEKoN0Q=""}",
             ExternalAccountId = externalAccountId
         };
         uow.AuthorizationTokenRepository.Add(tokenDO);
         uow.SaveChanges();
     }
 }
        private async Task <Guid> CreatePlan_GetSalesforceDataIntoSendEmail(AuthorizationTokenDO authToken)
        {
            //get required activity templates
            var activityTemplates = await HttpGetAsync <IEnumerable <ActivityTemplateCategoryDTO> >(_baseUrl + "activity_templates");

            var getData   = activityTemplates.Single(at => at.Name.Equals("Receivers")).Activities.Single(a => a.Name.Equals("Get_Data"));
            var sendEmail = activityTemplates.Single(at => at.Name.Equals("Forwarders")).Activities.Single(a => a.Name.Equals("Send_Email_Via_SendGrid"));

            Assert.IsNotNull(getData, "Get Salesforce Data activity is not available");
            Assert.IsNotNull(sendEmail, "Send Email activity is not available");
            Debug.WriteLine("Got required activity templates.");

            //create initial plan
            var initialPlan = await HttpPostAsync <PlanNoChildrenDTO, PlanDTO>(_baseUrl + "plans", new PlanNoChildrenDTO()
            {
                Name = "GetSalesforceData_Into_SendEmail_EndToEnd_Test"
            });

            Debug.WriteLine("Created initial plan without actions");

            string mainUrl          = _baseUrl + "activities/create";
            var    postUrl          = "?activityTemplateId={0}&createPlan=false";
            var    formattedPostUrl = string.Format(postUrl, getData.Id);

            formattedPostUrl += "&parentNodeId=" + initialPlan.StartingSubPlanId;
            formattedPostUrl += "&authorizationTokenId=" + authToken.Id.ToString();
            formattedPostUrl += "&order=" + 1;
            formattedPostUrl  = mainUrl + formattedPostUrl;
            var getDataActivity = await HttpPostAsync <ActivityDTO>(formattedPostUrl, null);

            Assert.IsNotNull(getDataActivity, "Initial Create and Configure of Get Salesforce Data action is failed.");
            Debug.WriteLine("Create and Initial Configure of Get Salesforce Data activity is successful.");

            formattedPostUrl  = string.Format(postUrl, sendEmail.Id);
            formattedPostUrl += "&parentNodeId=" + initialPlan.StartingSubPlanId;
            formattedPostUrl += "&order=" + 2;
            formattedPostUrl  = mainUrl + formattedPostUrl;
            var sendEmailActivity = await HttpPostAsync <ActivityDTO>(formattedPostUrl, null);

            Assert.IsNotNull(sendEmailActivity, "Initial Create and Configure of Send Email action is failed.");
            Debug.WriteLine("Create and Initial Configure of Send Email activity is successful.");

            return(initialPlan.Id);
        }
Пример #15
0
        private void AuthTokenCreated(AuthorizationTokenDO authToken)
        {
            var factDO = new FactDO();

            factDO.PrimaryCategory   = "AuthToken";
            factDO.SecondaryCategory = "Created";
            factDO.Activity          = "AuthToken Created";
            factDO.ObjectId          = null;
            factDO.CreatedByID       = _security.GetCurrentUser();
            factDO.Data = string.Join(
                Environment.NewLine,
                "AuthToken method: Created",
                "User Id: " + authToken.UserID.ToString(),
                "Terminal name: " + FormatTerminalName(authToken),
                "External AccountId: " + authToken.ExternalAccountId
                );

            SaveAndLogFact(factDO);
        }
Пример #16
0
        private void AuthTokenRemoved(AuthorizationTokenDO authToken)
        {
            var newFactDO = new FactDO
            {
                PrimaryCategory   = "AuthToken",
                SecondaryCategory = "Removed",
                Activity          = "AuthToken Removed",
                ObjectId          = null,
                CreatedByID       = _security.GetCurrentUser(),
                Data = string.Join(
                    Environment.NewLine,
                    "AuthToken method: Removed",
                    "User Id: " + authToken.UserID.ToString(),
                    "Terminal name: " + FormatTerminalName(authToken),
                    "External AccountId: " + authToken.ExternalAccountId
                    )
            };

            SaveAndLogFact(newFactDO);
        }
Пример #17
0
        private void AuthTokenSilentRevoke(AuthorizationTokenDO authToken)
        {
            var incident = new IncidentDO
            {
                Fr8UserId = _sercurity.GetCurrentUser(),
                Data      = string.Join(
                    Environment.NewLine,
                    "AuthToken method: Silent Revoke",
                    "User Id: " + authToken.UserID.ToString(),
                    "Terminal name: " + FormatTerminalName(authToken),
                    "External AccountId: " + authToken.ExternalAccountId
                    ),
                PrimaryCategory   = "AuthToken",
                SecondaryCategory = "Silent Revoke",
                Component         = "Hub",
                Activity          = "AuthToken Silent Revoke"
            };

            SaveAndLogIncident(incident);
        }
        private async Task AddAndAuthorizeMonitorGmailInboxActivity(AuthorizationTokenDO token, PlanDTO testPlan)
        {
            var gmailMonitorActivity = await _googleActivityConfigurator.CreateMonitorGmailInbox(testPlan, 1);

            gmailMonitorActivity.CrateStorage = new CrateStorageDTO();
            var tokenDTO = AutoMapper.Mapper.Map <AuthorizationTokenDTO>(token);

            var applyToken = new AuthenticationTokenGrantDTO()
            {
                ActivityId  = gmailMonitorActivity.Id,
                AuthTokenId = Guid.Parse(tokenDTO.Id),
                IsMain      = false
            };

            await HttpPostAsync <AuthenticationTokenGrantDTO[], string>(GetHubApiBaseUrl() + "authentication/tokens/grant", new[] { applyToken });

            gmailMonitorActivity = await _googleActivityConfigurator.SaveActivity(gmailMonitorActivity);

            gmailMonitorActivity = await _googleActivityConfigurator.ConfigureActivity(gmailMonitorActivity);
        }
Пример #19
0
        private AuthorizationTokenDO CreateAndAddTokenDO()
        {
            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                var terminalDO = CreateAndAddTerminalDO();
                var userDO     = CreateAndAddUserDO();

                var tokenDO = new AuthorizationTokenDO()
                {
                    UserID     = userDO.Id,
                    TerminalID = terminalDO.Id,
                    AuthorizationTokenState = AuthorizationTokenState.Active
                };
                uow.AuthorizationTokenRepository.Add(tokenDO);

                tokenDO.Token = Token;
                uow.SaveChanges();

                return(tokenDO);
            }
        }
        /*********************************************************************************/

        private AuthorizationTokenDO Track(AuthorizationTokenDO token, EntityState state)
        {
            AuthorizationTokenChangeTracker changeTracker;

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

            if (!_changesTackers.TryGetValue(token.Id, out changeTracker))
            {
                changeTracker = new AuthorizationTokenChangeTracker(token, state);

                _changesTackers[token.Id] = changeTracker;
            }
            else
            {
                changeTracker.State = state;
            }

            return(changeTracker.ActualValue);
        }
        private void GetDifferentGoogleAuthToken(out Fr8AccountDO currentUser, out AuthorizationTokenDO token)
        {
            using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
            {
                currentUser = uow.UserRepository.GetQuery().Where(a => a.UserName == TestUserEmail).FirstOrDefault();

                var googleTerminalId = uow.TerminalRepository.FindOne(t => t.Name.Equals("terminalGoogle")).Id;
                token = uow.AuthorizationTokenRepository.FindTokenByExternalAccount(GoogleEmail, googleTerminalId, currentUser.Id);
                if (token == null)
                {
                    token                   = new AuthorizationTokenDO();
                    token.Token             = FixtureData.GetGoogleAuthorizationTokenForGmailMonitor();
                    token.CreateDate        = DateTime.Now;
                    token.LastUpdated       = DateTime.Now;
                    token.TerminalID        = googleTerminalId;
                    token.UserID            = currentUser.Id;
                    token.ExternalAccountId = GoogleEmail;
                    uow.AuthorizationTokenRepository.Add(token);
                    uow.SaveChanges();
                    token = uow.AuthorizationTokenRepository.FindTokenByExternalAccount(GoogleEmail, googleTerminalId, currentUser.Id);
                }
            }
        }
Пример #22
0
        private void RemoveToken(IUnitOfWork uow, AuthorizationTokenDO authToken)
        {
            EventManager.AuthTokenRemoved(authToken);

            var activities = uow.PlanRepository.GetActivityQueryUncached()
                             .Where(x => x.AuthorizationToken.Id == authToken.Id)
                             .ToList();


            foreach (var activity in activities)
            {
                activity.AuthorizationToken = null;
                uow.PlanRepository.RemoveAuthorizationTokenFromCache(activity);
            }

            authToken = uow.AuthorizationTokenRepository.GetPublicDataQuery().FirstOrDefault(x => x.Id == authToken.Id);
            if (authToken != null)
            {
                uow.AuthorizationTokenRepository.Remove(authToken);
            }

            //Deactivating active related plans
            var _plan = ObjectFactory.GetInstance <IPlan>();
            var plans = new List <PlanDO>();

            foreach (var activity in activities)
            {
                //if template has Monitor category
                if (activity.ActivityTemplate.Categories.Where(a => a.ActivityCategoryId == ActivityCategories.MonitorId).FirstOrDefault() != null)
                {
                    _plan.Deactivate(activity.RootPlanNodeId.Value);
                }
            }

            uow.SaveChanges();
        }
Пример #23
0
 public void ResetChanges()
 {
     Changes = null;
     State   = EntityState.Modified;
     _propertiesTrackingReference = _tokenInstance.Clone();
 }
Пример #24
0
 public AuthorizationTokenChangeTracker(AuthorizationTokenDO tokenInstance, EntityState state)
 {
     State          = state;
     _tokenInstance = tokenInstance;
     _propertiesTrackingReference = _tokenInstance.Clone();
 }
Пример #25
0
 protected virtual void Configure(AuthorizationTokenDO token)
 {
 }
Пример #26
0
 protected virtual void Initialize(AuthorizationTokenDO token)
 {
 }
Пример #27
0
 protected virtual void Run(AuthorizationTokenDO token)
 {
 }
Пример #28
0
        public async Task SaveToSalesforce_And_GetSalesforceData_EndToEnd()
        {
            AuthorizationTokenDO authTokenDO        = null;
            AuthorizationToken   authorizationToken = null;
            Guid   initialPlanId = Guid.Empty;
            string newLeadId     = string.Empty;

            try
            {
                authTokenDO = await Fixtures.HealthMonitor_FixtureData.CreateSalesforceAuthToken();

                authorizationToken = new AuthorizationToken
                {
                    UserId               = authTokenDO.UserID,
                    ExternalAccountId    = authTokenDO.ExternalAccountId,
                    ExternalDomainId     = authTokenDO.ExternalDomainId,
                    AdditionalAttributes = authTokenDO.AdditionalAttributes,
                    Token = authTokenDO.Token,
                    Id    = authTokenDO.Id.ToString()
                };
                //Create the required plan with all initial activities initial config
                initialPlanId = await CreatePlan_SaveAndGetDataFromSalesforce(authTokenDO);

                //get the full plan which is created
                var plan = await HttpGetAsync <PlanDTO>(_baseUrl + "Plans?include_children=true&id=" + initialPlanId.ToString());

                Debug.WriteLine("Created plan with all activities.");

                //prepare the two activities with their follow up config
                await PrepareSaveToLead(plan);
                await PrepareGetData(plan);

                //execute the plan
                Debug.WriteLine("Executing plan " + plan.Name);
                var container = await HttpPostAsync <string, ContainerDTO>(_baseUrl + "plans/run?planId=" + plan.Id.ToString(), null);

                Debug.WriteLine("Executing plan " + plan.Name + " successful.");

                //get the payload of the executed plan
                var payload = await HttpGetAsync <PayloadDTO>(_baseUrl + "Containers/payload?id=" + container.Id.ToString());

                Debug.WriteLine("Got the payload for the container " + container.Name);

                //Assert
                Debug.WriteLine("Asserting initial payload.");
                var payloadList = Crate.GetUpdatableStorage(payload).CratesOfType <StandardPayloadDataCM>().ToList();
                Assert.AreEqual(1, payloadList.Count, "The payload does not contain all activities payload");
                Assert.IsTrue(payloadList.Any(pl => pl.Label.Equals("Lead is saved in Salesforce.com")), "Save Data is Failed to save the lead.");

                Debug.WriteLine("Asserting Save To Salesforce payload.");
                var savePayload = payloadList[0].Content.PayloadObjects[0].PayloadObject;
                Assert.AreEqual(1, savePayload.Count, "Save data payload contains some unwanted fields.");
                Assert.IsTrue(savePayload.Any(f => f.Key.Equals("LeadID")), "The newly created lead ID is not populated in the run time.");

                newLeadId = savePayload.Single(f => f.Key.Equals("LeadID")).Value;
                Debug.WriteLine("Newly created Lead ID is " + newLeadId);

                Debug.WriteLine("Deleting newly created lead with " + newLeadId);
                var isDeleted = await _container.GetInstance <SalesforceManager>().Delete(SalesforceObjectType.Lead, newLeadId, authorizationToken);

                Assert.IsTrue(isDeleted, "The newly created Lead for integration test purpose is not deleted.");
                newLeadId = string.Empty;

                Debug.WriteLine("Cleaning up.");
                await CleanUp(authorizationToken, initialPlanId, newLeadId);

                Debug.WriteLine("Cleaning up Successful.");
            }
            finally
            {
                await CleanUp(authorizationToken, initialPlanId, newLeadId);
            }
        }
Пример #29
0
 public ChangedToken(AuthorizationTokenDO token, List <IMemberAccessor> changedProperties)
 {
     Token             = token;
     ChangedProperties = changedProperties;
 }
Пример #30
0
        public async Task <PayloadDTO> ExecuteChildActivities(ActivityDO curActivityDO, Guid containerId, AuthorizationTokenDO authTokenDO)
        {
            AddCrateMethodInvoked("ExecuteChildActivities");
            var processPayload = new PayloadDTO(Guid.NewGuid());

            return(await Task.FromResult(processPayload));
        }