private async Task <SalesforceUser> MapActiveDirectoryUserToSalesforceUser(AzureActiveDirectoryUser user) { var operatingSystemTask = CheckUserFranchiseAgainstFranchiseSource(user, ProgramDataSources.ClearCare, "ClearCare", "N/A"); var timeZoneTask = _timeZoneService.RetrieveTimeZoneAndPopulateUsersCountryCode(user); await Task.WhenAll(operatingSystemTask, timeZoneTask); var salesforceUser = new SalesforceUser { FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, FranchiseNumber = user.FranchiseNumber, ExternalId = user.ExternalId, FederationId = user.FederationId, MobilePhone = user.MobilePhone, Address = user.Address, City = user.City, State = user.State, PostalCode = user.PostalCode, CountryCode = user.CountryCode, IsOwner = user.IsOwner, Title = user.Title, OperatingSystem = await operatingSystemTask, TimeZone = await timeZoneTask }; return(salesforceUser); }
public override IEnumerable <ISalesforceUser> FindAccountsForService(string serviceId) { var r = new List <SalesforceUser> (); var postfix = "-" + serviceId; var aliases = ks.Aliases(); while (aliases.HasMoreElements) { var alias = aliases.NextElement().ToString(); if (alias.EndsWith(postfix)) { var e = ks.GetEntry(alias, prot) as KeyStore.SecretKeyEntry; if (e != null) { var bytes = e.SecretKey.GetEncoded(); var serialized = System.Text.Encoding.UTF8.GetString(bytes); var acct = SalesforceUser.Deserialize(serialized); r.Add(acct); } } } r.Sort((a, b) => a.Username.CompareTo(b.Username)); return(r); }
public void Setup () { var key = "3MVG9A2kN3Bn17hueOTBLV6amupuqyVHycNQ43Q4pIHuDhYcP0gUA0zxwtLPCcnDlOKy0gopxQ4dA6BcNWLab"; var redirectUrl = new Uri("com.sample.salesforce:/oauth2Callback"); // TODO: Move oauth redirect to constant or config var secret = "5754078534436456018"; Client = new SalesforceClient (key, secret, redirectUrl); var users = Client.LoadUsers (); ISalesforceUser user; if (users.SingleOrDefault() == null) { user = new SalesforceUser { Username = "******", }; user.Properties ["instance_url"] = @"https://na15.salesforce.com/"; user.Properties ["access_token"] = @"00Di0000000bhOg!ARYAQLWetbW6H_Lw78K0SlJ3IU7bBCeOMEhtlP8hTvaWALsYNuxfkikbC5tbAfgdNvxjSkZJ6wHVr8A5qIKM7.KeBmGnoIlg"; Client.Save (user); } else { user = users.FirstOrDefault (); } Client.CurrentUser = user; }
/// <summary> /// Restores an account from its serialized string representation. /// </summary> /// <param name='serializedString'> /// The serialized account generated by <see cref="Serialize"/> /// </param> public static SalesforceUser Deserialize(string serializedString) { var acct = new SalesforceUser(); foreach (var p in serializedString.Split('&')) { var kv = p.Split('='); var key = Uri.UnescapeDataString(kv[0]); var val = kv.Length > 1 ? Uri.UnescapeDataString(kv[1]) : ""; if (key == "__cookies__") { acct.Cookies = DeserializeCookies(val); } else if (key == "__username__") { acct.Username = val; } else if (key == "force_expiry") { acct.RequiresReauthentication = Boolean.Parse(val); } else { acct.Properties[key] = val; } } return(acct); }
public void Setup() { var key = "3MVG9A2kN3Bn17hueOTBLV6amupuqyVHycNQ43Q4pIHuDhYcP0gUA0zxwtLPCcnDlOKy0gopxQ4dA6BcNWLab"; var redirectUrl = new Uri("com.sample.salesforce:/oauth2Callback"); // TODO: Move oauth redirect to constant or config var secret = "5754078534436456018"; Client = new SalesforceClient(key, secret, redirectUrl); var users = Client.LoadUsers(); ISalesforceUser user; if (users.SingleOrDefault() == null) { user = new SalesforceUser { Username = "******", }; user.Properties ["instance_url"] = @"https://na15.salesforce.com/"; user.Properties ["access_token"] = @"00Di0000000bhOg!ARYAQLWetbW6H_Lw78K0SlJ3IU7bBCeOMEhtlP8hTvaWALsYNuxfkikbC5tbAfgdNvxjSkZJ6wHVr8A5qIKM7.KeBmGnoIlg"; Client.Save(user); } else { user = users.FirstOrDefault(); } Client.CurrentUser = user; }
/// <summary> /// Implementations must call this function when they have successfully authenticated. /// </summary> /// <param name='account'> /// The authenticated account. /// </param> public void OnSucceeded(SalesforceUser account) { BeginInvokeOnUIThread(delegate { var ev = Completed; if (ev != null) { ev(this, new AuthenticatorCompletedEventArgs(account)); } }); }
public async void Setup() { var key = "3MVG9A2kN3Bn17hueOTBLV6amupuqyVHycNQ43Q4pIHuDhYcP0gUA0zxwtLPCcnDlOKy0gopxQ4dA6BcNWLab"; var redirectUrl = new Uri("com.sample.salesforce:/oauth2Callback"); var secret = "5754078534436456018"; Client = new SalesforceClient(key, secret, redirectUrl); // Use username/password flow for the demo. // This ensures we always have a valid // access_token for about 6 hours after this // method returns. var tokenClient = new HttpClient(); var formData = new Dictionary <string, string> { { "grant_type", "password" }, { "client_id", "3MVG9A2kN3Bn17hueOTBLV6amupuqyVHycNQ43Q4pIHuDhYcP0gUA0zxwtLPCcnDlOKy0gopxQ4dA6BcNWLab" }, { "client_secret", "5754078534436456018" }, { "username", "*****@*****.**" }, { "password", "white1@needyrVpFxD3PAvjdH8svH7wLXTN98" }, }; var content = new FormUrlEncodedContent(formData); var responseTask = await tokenClient.PostAsync("https://login.salesforce.com/services/oauth2/token", content); // responseTask.RunSynchronously(TaskScheduler.Default); // responseTask.Wait(); responseTask.EnsureSuccessStatusCode(); var responseReadTask = await responseTask.Content.ReadAsStringAsync(); // var rawResult = await response.Content.ReadAsStringAsync(); // responseReadTask.RunSynchronously(); // responseReadTask.Wait(); // var result = JsonValue.Parse(rawResult); var result = JsonValue.Parse(responseReadTask); var users = Client.LoadUsers(); ISalesforceUser user; if (users.FirstOrDefault() == null) { user = new SalesforceUser { Username = "******", }; user.Properties ["instance_url"] = @"https://na15.salesforce.com"; user.Properties ["refresh_token"] = @"5Aep861z80Xevi74eVVu3JCJRUeNrRZAcxky4UcHL1MvM2ALL3Wj_phoRIBXVC2ZcbP_BblUk39RfBF6cwu.lx3"; user.Properties ["access_token"] = result["access_token"]; //@"00Di0000000bhOg!ARYAQN2uT2p0I.g1t03eAfogW8ZostVE61ZTMkkrOb1eiWADj9vEABhGUqqO05PQNdUA4pq60a3JTPTwyN6Z7blXpZXJbyHX"; user.Properties ["requires_reauthentication"] = "false"; Client.Save(user); } else { user = users.FirstOrDefault(); } Client.CurrentUser = user; }
public async Task <string> InviteUser(SalesforceUser SFUser) { Invitation invitation = new Invitation(); invitation.invitedUserEmailAddress = SFUser.EMail; invitation.inviteRedirectUrl = "http://Revature_housing_homepage:8080"; invitation.sendInvitationMessage = true; var json = JsonConvert.SerializeObject(invitation); return(await PostInvitation("/invitations", json)); }
public async void Setup () { var key = "3MVG9A2kN3Bn17hueOTBLV6amupuqyVHycNQ43Q4pIHuDhYcP0gUA0zxwtLPCcnDlOKy0gopxQ4dA6BcNWLab"; var redirectUrl = new Uri("com.sample.salesforce:/oauth2Callback"); var secret = "5754078534436456018"; Client = new SalesforceClient (key, secret, redirectUrl); // Use username/password flow for the demo. // This ensures we always have a valid // access_token for about 6 hours after this // method returns. var tokenClient = new HttpClient(); var formData = new Dictionary<string,string> { {"grant_type", "password"}, {"client_id", "3MVG9A2kN3Bn17hueOTBLV6amupuqyVHycNQ43Q4pIHuDhYcP0gUA0zxwtLPCcnDlOKy0gopxQ4dA6BcNWLab"}, {"client_secret", "5754078534436456018"}, {"username", "*****@*****.**"}, {"password", "white1@needyrVpFxD3PAvjdH8svH7wLXTN98"}, }; var content = new FormUrlEncodedContent(formData); var responseTask = await tokenClient.PostAsync("https://login.salesforce.com/services/oauth2/token", content); // responseTask.RunSynchronously(TaskScheduler.Default); // responseTask.Wait(); responseTask.EnsureSuccessStatusCode(); var responseReadTask = await responseTask.Content.ReadAsStringAsync(); // var rawResult = await response.Content.ReadAsStringAsync(); // responseReadTask.RunSynchronously(); // responseReadTask.Wait(); // var result = JsonValue.Parse(rawResult); var result = JsonValue.Parse(responseReadTask); var users = Client.LoadUsers (); ISalesforceUser user; if (users.FirstOrDefault() == null) { user = new SalesforceUser { Username = "******", }; user.Properties ["instance_url"] = @"https://na15.salesforce.com"; user.Properties ["refresh_token"] = @"5Aep861z80Xevi74eVVu3JCJRUeNrRZAcxky4UcHL1MvM2ALL3Wj_phoRIBXVC2ZcbP_BblUk39RfBF6cwu.lx3"; user.Properties ["access_token"] = result["access_token"]; //@"00Di0000000bhOg!ARYAQN2uT2p0I.g1t03eAfogW8ZostVE61ZTMkkrOb1eiWADj9vEABhGUqqO05PQNdUA4pq60a3JTPTwyN6Z7blXpZXJbyHX"; user.Properties ["requires_reauthentication"] = "false"; Client.Save (user); } else { user = users.FirstOrDefault (); } Client.CurrentUser = user; }
/// <summary> /// Gets an authenticated HTTP Authorization header. /// </summary> /// <returns> /// The authorization header. /// </returns> /// <param name='account'> /// The <see cref="Account"/> that's been authenticated. /// </param> public static string GetAuthorizationHeader(SalesforceUser account) { if (account == null) { throw new ArgumentNullException("account"); } if (!account.Properties.ContainsKey("access_token")) { throw new ArgumentException("OAuth2 account is missing required access_token property.", "account"); } return("Bearer " + account.Properties ["access_token"]); }
private static string TruncateSalesforceId(SalesforceUser user, string defaultId) { if (user != null) { if (user.SalesforceId.Length > 15) { return(user.SalesforceId.Substring(0, 15)); } else { return(user.SalesforceId); } } return(defaultId); }
private async Task <SalesforceUser> GetSalesforceUserCreatingNewIfNecessary(string id) { if (id == null) { return(null); } SalesforceUser user = null; if (!recordingsDb.SalesforceUsers.Any(u => u.SalesforceIdCode == id)) { user = new SalesforceUser(id); recordingsDb.SalesforceUsers.Add(user); await recordingsDb.SaveChangesAsync(); return(user); } return(recordingsDb.SalesforceUsers.Single(u => u.SalesforceIdCode == id)); }
public async Task <ActionResult> Record(int?id) { if (id == helper.RecordFailureRouteValue) { ViewBag.RecordFailure = "Recording failed, please try again."; } SalesforceUser user = await helper.GetCurrentUser(this); if (helper.LoginRedirectNeeded(this)) { return(helper.RedirectToLogin(this)); } if (user == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Session[helper.UserKey] = user; return(View()); }
private MyProfileInformation MapToProfileInformation(SalesforceUser userData, MyProfileInformation defaultProfile) { if (userData == null) { return(defaultProfile); } return(new MyProfileInformation() { Address1 = userData.Street, city = userData.City, Email = userData.Email, Firstname = userData.FirstName, Lastname = userData.LastName, zipcode = userData.PostalCode, State = userData.State, UserID = userData.SalesforceId }); }
public async Task <ActionResult> Recorded() { byte[] audioBytes = null; HttpPostedFileBase file = null; SalesforceUser user = Session[helper.UserKey] as SalesforceUser; DateTimeOffset recordingTime = DateTime.Now; SpeechToTextGoogleAPI googleInterpreter = new SpeechToTextGoogleAPI(); if (Request.Files.Count < 1) { return(RedirectToAction("Record", new { id = helper.RecordFailureRouteValue })); } foreach (string upload in Request.Files) { file = Request.Files[upload]; if (file == null) { continue; } audioBytes = new byte[file.ContentLength]; } //Only want the one file, will default to last file iterated and write to the audioBytes file.InputStream.Read(audioBytes, 0, file.ContentLength); AudioBinary audioBinary = new AudioBinary(audioBytes, AudioType.Wav); RecordingText googleText = InterpreterDirector.TranslateSpeechToText(audioBinary, googleInterpreter); Recording newRecording = new Recording(user, recordingTime, audioBinary); recordingsDb.Recordings.Add(newRecording); await recordingsDb.SaveChangesAsync(); recordingsDb.AudioBinarys.Add(audioBinary); await recordingsDb.SaveChangesAsync(); recordingsDb.RecordingTexts.Add(googleText); await recordingsDb.SaveChangesAsync(); return(RedirectToAction("index", new { id = newRecording.ID })); }
public async Task <SalesforceUser> GetCurrentUser(Controller caller) { IEnumerable <AuthSession> sessions = Enumerable.Empty <AuthSession>(); string id = null; SalesforceUser user = null; string userQuery = "SELECT UsersId From AuthSession"; try { sessions = await SalesforceRequest <AuthSession>(userQuery); id = sessions.FirstOrDefault().UsersId; } catch (Exception ex) { CatchSalesforceRequest(caller, ex, "Getting user Id through AuthSession"); } if (id != null) { user = await GetSalesforceUserCreatingNewIfNecessary(id); } return(user); }
/// <summary> /// Implementations must call this function when they have successfully authenticated. /// </summary> /// <param name='account'> /// The authenticated account. /// </param> public void OnSucceeded (SalesforceUser account) { BeginInvokeOnUIThread (delegate { var ev = Completed; if (ev != null) { ev (this, new AuthenticatorCompletedEventArgs (account)); } }); }
ISalesforceUser GetAccountFromRecord(SecRecord r) { var serializedData = NSString.FromData(r.Generic, NSStringEncoding.UTF8); return(SalesforceUser.Deserialize(serializedData)); }
/// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.OAuth1Request"/> class. /// </summary> /// <param name='method'> /// The HTTP method. /// </param> /// <param name='url'> /// The URL. /// </param> /// <param name='parameters'> /// Parameters that will pre-populate the <see cref="Xamarin.Auth.Request.Parameters"/> property or <see langword="null"/>. /// </param> /// <param name='account'> /// The account used to authenticate this request. /// </param> /// <param name='includeMultipartsInSignature'> /// If set to <see langword="true"/> include multiparts when calculating the OAuth 1.0 signature. /// </param> public OAuth1Request (string method, Uri url, IDictionary<string, string> parameters, SalesforceUser account, bool includeMultipartsInSignature = false) : base (method, url, parameters, account) { this.includeMultipartsInSignature = includeMultipartsInSignature; }
/// <summary> /// Restores an account from its serialized string representation. /// </summary> /// <param name='serializedString'> /// The serialized account generated by <see cref="Serialize"/> /// </param> public static SalesforceUser Deserialize (string serializedString) { var acct = new SalesforceUser (); foreach (var p in serializedString.Split ('&')) { var kv = p.Split ('='); var key = Uri.UnescapeDataString (kv [0]); var val = kv.Length > 1 ? Uri.UnescapeDataString (kv [1]) : ""; if (key == "__cookies__") { acct.Cookies = DeserializeCookies (val); } else if (key == "__username__") { acct.Username = val; } else if (key == "force_expiry") { acct.RequiresReauthentication = Boolean.Parse(val); } else { acct.Properties [key] = val; } } return acct; }
/// <summary> /// Gets an authenticated HTTP Authorization header. /// </summary> /// <returns> /// The authorization header. /// </returns> /// <param name='account'> /// The <see cref="Account"/> that's been authenticated. /// </param> public static string GetAuthorizationHeader (SalesforceUser account) { if (account == null) { throw new ArgumentNullException ("account"); } if (!account.Properties.ContainsKey ("access_token")) { throw new ArgumentException ("OAuth2 account is missing required access_token property.", "account"); } return "Bearer " + account.Properties ["access_token"]; }
/// <summary> /// Initializes a new instance of the <see cref="Xamarin.Auth.OAuth1Request"/> class. /// </summary> /// <param name='method'> /// The HTTP method. /// </param> /// <param name='url'> /// The URL. /// </param> /// <param name='parameters'> /// Parameters that will pre-populate the <see cref="Xamarin.Auth.Request.Parameters"/> property or <see langword="null"/>. /// </param> /// <param name='account'> /// The account used to authenticate this request. /// </param> /// <param name='includeMultipartsInSignature'> /// If set to <see langword="true"/> include multiparts when calculating the OAuth 1.0 signature. /// </param> public OAuth1Request(string method, Uri url, IDictionary <string, string> parameters, SalesforceUser account, bool includeMultipartsInSignature = false) : base(method, url, parameters, account) { this.includeMultipartsInSignature = includeMultipartsInSignature; }
public static SSOMessage BuildMarcomCentralAuthenticationRequest(string aplId, string pageName, string productId) { SSOMessage ssoMessage = null; NameValueCollection settings = null; NameValueCollection impersonatingSettings = null; AgentDetails agentData = null; IEnumerable <SupportTeamDetails> supportTeamData = null; MyProfileInformation profileData = null; MyProfileInformation impersonatingProfileData = null; SalesforceUser impersonatingSalesforceUser = null; SalesforceUser salesforceInternalUser = null; string settingsItemPath = "/sitecore/content/Home/Marketing/Portal"; string settingsTemplate = "Marcom Central Setting"; string settingsField = "Settings"; string userGroupNameField = "User Group Name"; string userGroupName = string.Empty; string impersonatingUserGroupName = string.Empty; string parameters = string.Empty; try { var client = new ServiceClient(); Authorization currentAuthorization = Authorization.CurrentAuthorization; var agents = currentAuthorization.Claim.Roles.Where(r => r.RoleId == 6).Select((a) => a.APLId).Distinct().ToArray(); var ssoDataAttributes = client.GetUserAttributes(currentAuthorization.Claim.LoggedInSSOGuid, null); bool isExternalUser = agents.Length > 0; string currentUserId = aplId; string marcomCentralUserId = string.Empty; string marcomCentralImpersonatingUserId = string.Empty; if (ssoDataAttributes != null && ssoDataAttributes.UserData != null) { var attributes = ssoDataAttributes.UserData.FirstOrDefault(); currentUserId = attributes.AplId; } bool isImpersonating = !string.IsNullOrWhiteSpace(currentUserId) && currentAuthorization.Claim.SSOGuid != currentAuthorization.Claim.LoggedInSSOGuid; var roleClaim = currentAuthorization.Claim.Roles.Where(r => r.APLId == aplId).FirstOrDefault(); var item = ContextExtension.CurrentDatabase.GetItem(settingsItemPath); if (item != null) { var itemList = item.GetChildrenOfTemplate(settingsTemplate).Where(i => HasChannel(i, roleClaim.ChannelType) && HasPCStatus(i, roleClaim.PC_Status)); var settingsItem = itemList.FirstOrDefault(); if (settingsItem != null) { parameters = settingsItem[settingsField]; userGroupName = settingsItem[userGroupNameField]; settings = Sitecore.Web.WebUtil.ParseUrlParameters(parameters); } } if (isImpersonating) { var impersonatingSettingsItem = ContextExtension.CurrentDatabase.GetItem(MarketingLogic.MarcomCentralImpersonatingSettingsPath); if (impersonatingSettingsItem != null) { parameters = impersonatingSettingsItem[settingsField]; impersonatingUserGroupName = impersonatingSettingsItem[userGroupNameField]; impersonatingSettings = Sitecore.Web.WebUtil.ParseUrlParameters(parameters); } } if (isExternalUser) { var agentDetailsResponse = client.GetAgentDetails(aplId); var supportTeamResponse = client.GetSupportTeamDetails(aplId); agentData = agentDetailsResponse.AgentDetails != null?agentDetailsResponse.AgentDetails.FirstOrDefault() : null; supportTeamData = supportTeamResponse.SupportTeamDetails; profileData = GetUserInfo(currentUserId); marcomCentralUserId = aplId; if (isImpersonating) { impersonatingProfileData = GetUserInfo(currentUserId); impersonatingSalesforceUser = GetSalesforceUser(currentUserId); marcomCentralImpersonatingUserId = marcomCentralUserId; marcomCentralUserId = TruncateSalesforceId(impersonatingSalesforceUser, currentUserId); } var regionalConsultant = supportTeamData != null?supportTeamData.Where(t => t.JobTitle == "Regional Consultant").FirstOrDefault() : null; var internalConsultant = supportTeamData != null?supportTeamData.Where(t => t.JobTitle == "Internal Consultant").FirstOrDefault() : null; string rcName = regionalConsultant != null ? regionalConsultant.FirstName + " " + regionalConsultant.LastName : string.Empty; string icName = internalConsultant != null ? internalConsultant.FirstName + " " + internalConsultant.LastName : string.Empty; string userName = string.Empty; if (isImpersonating) { userName = impersonatingProfileData != null ? impersonatingProfileData.Firstname + " " + impersonatingProfileData.Lastname : string.Empty; } else { userName = profileData != null ? profileData.Firstname + " " + profileData.Lastname : string.Empty; } settings.Add("User.GenericField1", userName.Trim()); settings.Add("User.GenericField2", agentData.PrimaryAdvisorID); settings.Add("User.GenericField3", rcName.Trim()); settings.Add("User.GenericField4", icName.Trim()); } else { // it's an internal user or employee profileData = GetUserInfo(aplId); salesforceInternalUser = GetSalesforceUser(aplId); marcomCentralUserId = TruncateSalesforceId(salesforceInternalUser, aplId); if (isImpersonating) { impersonatingProfileData = GetUserInfo(currentUserId); impersonatingSalesforceUser = GetSalesforceUser(currentUserId); marcomCentralImpersonatingUserId = marcomCentralUserId; marcomCentralUserId = TruncateSalesforceId(impersonatingSalesforceUser, currentUserId); } } var mapper = new MarcomCentralDataMapper() { MarcomCentralUserId = marcomCentralUserId, MarcomCentralImpersonatingUserId = marcomCentralImpersonatingUserId, SalesforceInternalUser = salesforceInternalUser, ImpersonatingSalesforceUser = impersonatingSalesforceUser, PageName = pageName, ProductId = productId, IsExternalUser = isExternalUser, IsImpersonating = isImpersonating, AgentData = agentData, SupportTeamDetails = supportTeamData, UserProfile = profileData, ImpersonatingUserProfile = impersonatingProfileData, Settings = settings, ImpersonatingSettings = impersonatingSettings, UserGroupName = userGroupName, ImpersonatingUserGroupName = impersonatingUserGroupName }; ssoMessage = mapper.MapToMarcomCentralData(); } catch (Exception ex) { Sitecore.Diagnostics.Log.Error("Unable to build Marcom Central authentication request for user " + aplId, ex, typeof(Controller)); } return(ssoMessage); }