Monday, October 12, 2020

Javascript: for-of loops

for...of iterates arrays, array-like objects, and generally any iterable (maps, sets, DOM collections). You can destructure the iterated item in place. On top of that, for...of has a short syntax.

const fruits = ['oranges', 'apples'];

for (const fruit of fruits) {  
   console.log(fruit);
}

// 'oranges'
// 'apples'

Note that in for-of loops you can use const. Think of it as a new const declaration being executed each time in a fresh scope.

The array method entries() can be used to access the index of the iterated item. The method returns at each iteration a pair of [index, item].

const arr = ['oranges', 'apples'];

for (const [index, elem] of arr.entries()) {
  console.log(`${index} -> ${elem}`);
}

// 0 -> oranges
// 1 -> apples

At each iteration arr.entries() returns a pair of index and value, which is destructured by const [index, elem] expression.

Iterating over an array of objects

Example 1:

const person = {
  name: 'John Smith',
  job: 'agent'
};

for (const [prop, value] of Object.entries(person)) {
  console.log(prop, value);
}

// 'name', 'John Smith'
// 'job', 'agent'

where Object.entries(person) returns an array of key and value tuples.

Example 2:

const persons = [
  { name: 'John Smith' },
  { name: 'Jane Doe' }
];

for (const { name } of persons) {  
   console.log(name);
}

// 'John Smith'
// 'Jane Doe'

The cycle for (const { name } of persons) iterates the objects of persons array, but also destructures the person object in place { name }.

Maps and Sets iteration

const names = new Map();
names.set(1, 'one');
names.set(2, 'two');

for (const [number, name] of names) {  
   console.log(number, name);
}


const colors = new Set(['white', 'blue', 'red', 'white']);

for (color of colors) {
   console.log(color);
}

String characters iteration

const message = 'hello';

for (const character of message) {  
   console.log(character);
}

// 'h'
// 'e'
// 'l'
// 'l'
// 'o'
Share This:    Facebook Twitter

Saturday, October 10, 2020

Javascript: In-Place Out-Of-Place Algorithms

In an in-place function, the changes made by the function remain after the call completes. In-place algorithms are sometimes called destructive, since the original input is modified during the function call.

"In-place" does not mean "without creating any additional variables!" Rather, it means "without creating a new copy of the input." In general, an in-place function will only create additional variables that are O(1) space.

An out-of-place function doesn't make any changes that are visible to other functions. Usually, those functions copy any data structures or objects before manipulating and changing them.

Here are two functions that do the same operation on an array, except one is in-place and the other is out-of-place:

function squareArrayInPlace(intArray) {

  intArray.forEach((int, index) => {
    intArray[index] *= int;
  });

  // NOTE: no need to return anything - we modified intArray in place
}


function squareArrayOutOfPlace(intArray) {

  // We allocate a new array that we'll fill in with the new values
  const squaredArray = [];

  intArray.forEach((int, index) => {
    squaredArray[index] = Math.pow(int, 2);
  });

  return squaredArray;
}

Working in-place is a good way to save time and space. An in-place algorithm avoids the cost of initializing or copying data structures, and it usually has an O(1) space cost.

But be careful: an in-place algorithm can cause side effects. Your input is altered, which can affect code outside of your function.

Generally, out-of-place algorithms are considered safer because they avoid side effects. You should only use an in-place algorithm if you're space constrained or you're positive you don't need the original input anymore, even for debugging.

Share This:    Facebook Twitter

Friday, June 26, 2020

Salesforce Apex: Tips and Tricks

Generate a set of Ids from a List of SObject
List<Account> accounts = [SELECT Id, Name FROM Account];
Set<Id> selectedIds = new Map<Id, SObject>(accounts).keySet();
System.debug(selectedIds);

Division of 2 numbers
public static Decimal divide(Integer numerator, Integer denominator) {
    Decimal result;
    if (denominator != 0) {
        result = Decimal.valueOf(Double.valueOf(numerator) / Double.valueOf(denominator));
        return result.setScale(2);
    }
    return 0;
}


Formatting time in Apex
https://paulforce.wordpress.com/2009/08/27/formatting-time-in-apex/
Share This:    Facebook Twitter

Sunday, March 8, 2020

Monday, February 17, 2020

Accepting third Party Identity in Salesforce

Single Sign-On (SSO)

A process that allows the network to access all authorized networks without having to separately log in to each resource - one password fits all.
  • Federated Authentication: uses SAML and industry standards protocols. It is the default form of single sign-on. When enabled:
    • Salesforce doesn't validate the user's password
    • The platform receives an assertion in an HTTP POST
  • Delegated Authentication: a Salesforce-specific technology. When enabled:
    • Salesforce will make a Web service call to an external client to validate credentials. The web service must be SOAP and accessible over the internet.
NOTE:
  • While setting up SSO, you need to set up My Domain to allow redirection of users to an identity provider and allow access to Salesforce through deep links.
  • When you have an external identity provider and configure SSO for your Salesforce org, Salesforce is then acting as a service provider. You can also enable Salesforce as an identity provider and use SSO to connect to a different service provider. Only the service provider needs to configure SSO.

SAML

  • An OASIS standard for single sign-on
  • Security Assertion Markup Language (XML-based)
  • Designed to exchange authorization and authentication data
  • Trust is established during SAML configuration
    • The IdP's public key certificate is stored on the service provider's system
    • The IdP includes its public key certificate with the service provider in its assertions while making those HTTP POST requests.
    • The service provider uses the certificate to validate that the digital signature originated from the IdP, thereby validating the integrity of assertion.
  • Assertions can be encrypted optionally.

SAML Components

In a SAML SSO scenario, there are 3 key parties involved:
  1. A user or principal, who requires access to a resource (like Salesforce), which is provided by the Service Provider.  
  2. The Identity provider authenticates the user on behalf of the service provider. The Identity Provider is typically an Identity Management platform such as Ping Federate or Active Directory Federation Services (ADFS) and issues a SAML assertion token which is consumed by the service provider to authenticate the user.
  3. Service Provider – the website containing the resources the user wants to access. Eg Salesforce if federated identity used
So whatever authenticates you, that is the identity provider, while the service provider is whatever you are trying to get to. To understand the difference in layman's terms, check out this post.

Types of SAML Flow

  1. IdP Initiated: IdP sends an unsolicited SAML assertion to Salesforce
  2. SP Initiated: Starts with Salesforce, which solicits a SAML assertion from the IdP



SP Initiated Flow is the recommended Salesforce best practice.
  • Has the best user experience
  • Is required for using SSO with Salesforce mobile and desktop applications
  • Supports deep links
Check this video to see how to implement SSO in Salesforce: https://www.youtube.com/watch?v=ucmyYJ3iQoA

Delegated Authentication



  • Enable delegated authentication for a specific organization by contacting salesforce.com support
  • Download the AuthenticationService WSDL
    • Generate server-side stub and add specific implementation details
  • Specify SSO gateway
  • Modify profiles (specify which profiles will be enabled)
  • User credentials are encrypted and passed from Salesforce to DAS
NOTE: Do not enable SSO for the System Administrator profile. If the identity provider is unavailable, administrators will not be able to access the org.

Considerations
  • Activated at the profile level
  • Requires a proxy server that Salesforce can access
    • More cost for infrastructure and maintenance
  • Requires a valid certificate if an SSL or HTTPS connection is used with the authentication service

Which method to use?

  • User ID/password when basic configuration is required
  • SAML to provide single sign-on for the Web and applications
  • Delegated authentication with older infrastructures
  • OAuth when building an API client or mobile application

SAML with Multiple ORGs & Considerations

  • Adding additional orgs to single sign-on with SAML is just configuration
  • Many possible topologies are available:
    • Single enterprise identity provider, multiple service provider orgs
    • One org as identity provider, others as service provider
  • Check this link for more information: "Configure SSO Across Multiple Salesforce Orgs"

External Authentication Providers

  • External Authentication Providers allow ‘Social Sign-on’ using OAuth 2.0 and can be used to provision accounts, thereby letting your users log in to your Salesforce org using their login credentials from a third-party service.
  • Salesforce provides external authentication providers for apps that support the OpenID Connect protocol, such as Apple, Facebook, Google, Facebook, LinkedIn, and Twitter.
  • For apps that don’t support the OpenID Connect protocol but support OAuth or other authentication protocols, Salesforce provides an Apex Auth.AuthProviderPluginClass abstract class. With this class, you can create a custom authentication provider. This repo demonstrates the use of a Salesforce Custom External Authentication.
  • Salesforce can also be used as an authorisation provider for other orgs

To set up an external authentication provider,
  • Set up the Authorization Provider (e.g. Facebook)
  • Create an Apex Registration Handler class. Check this link for sample code.
  • Define the Authentication Provider in the Org
  • Add the button (e.g. Facebook) to the Login Page

EXAMPLE: How to set up Google as an external authentication provider?

  • Create an OAuth Client ID of type of web application in Google.
  • Set up an authorization provider like below, and provide the consumer key and secret.
  • Update the redirect URI in the OAuth client ID with the callback URL generated after creating the auth provider.
  • Add the Google sign-in button by updating the Authentication Configuration in My Domain.

Just-in-Time Provisioning for SAML

  • With Just-in-Time provisioning, you can use a SAML assertion to create regular and portal users on the fly the first time they try to log in. This eliminates the need to create user accounts in advance. 
  • For example, if you recently added an employee to your organization, you don't need to manually create the user in Salesforce. When they log in with single sign-on, their account is automatically created for them, eliminating the time and effort with on-boarding the account. 
  • Just-in-Time provisioning works with your SAML identity provider to pass the correct user information to Salesforce in a SAML 2.0 assertion. You can both create and modify accounts this way. 
  • Because Just-in-Time provisioning uses SAML to communicate, your organization must have SAML-based single sign-on enabled.
  • JIT provisioning uses attributes in the SAML assertion to create and update user records in Salesforce.
  • The SAML assertion must provide (at least):
    • Email
    • LastName
    • UserName
    • ProfileId - 15 character ID or profile name
  • It can also include any other optional attributes, such as
    • FirstName
    • Phone
    • Manager

Troubleshooting SAML

  • In Salesforce, from Setup, enter Single Sign-On Settings in the Quick Find box, then select Single Sign-On Settings.
  • Click SAML Assertion Validator. The SAML Validator shows the last recorded SAML login failure with some details as to why it failed.
  • To test the SAML assertion from the Axiom app, copy the Formatted SAML Response from the Axiom app.
  • In the Salesforce SAML Validator, paste the SAML assertion in the SAML Response box at the bottom of the page.
  • Click Validate. The page displays some results to help you troubleshoot the assertion. For example, if the assertion was generated a while before it was used to log in, the timestamp expires and the login isn’t valid. In that case, regenerate the SAML assertion and try again.
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top