Wednesday, 29 July 2015

External Organization-Wide Defaults Overview

External Organization-Wide Defaults Overview


External organization-wide defaults provide separate organization-wide defaults for internal and external users. They simplify your sharing rules configuration and improve recalculation performance. Additionally, administrators can easily see which information is being shared to portals and other external users.
The following objects support external organization-wide defaults.
  • Accounts and their associated contracts and assets
  • Cases
  • Contacts
  • Opportunities
  • Custom Objects
  • Users
External users include:
  • Authenticated website users
  • Chatter external users
  • Community users
  • Customer Portal users
  • Guest users
  • High-volume portal users
  • Partner Portal users
  • Service Cloud Portal users


****Chatter external users have access to the User object only.

Previously, if your organization wanted Public Read Only or Public Read/Write access for internal users but Private for external users, you would have to set the default access to Private and create a sharing rule to share records with all internal users.
With separate organization-wide defaults, you can achieve similar behavior by setting the default internal access to Public Read Onlyor Public Read/Write and the default external access to Private. These settings also speed up performance for reports, list views, searches, and API queries.

Friday, 24 July 2015

Creating, Assigning and Checking Custom Permissions


Creating, Assigning and Checking Custom Permissions

I have been wanting to explore Custom Permissions for a little while now, since they are now GA in Winter’15 i thought its about time i got stuck in. Profiles, Permission Sets have until recently, been focusing on granting permissions to entities only known to the platform, such as objectsfieldsApex classes and Visualforce pages. In most cases these platform entities map to a specific feature in your application you want to provide permission to access.
However there are cases where this is not always that simple. For example consider a Visualforce page you that controls a given process in your application, it has three buttons on it RunClear History and Reset. You can control access to the page itself, but how do you control access to the three buttons? What you need is to be able to teach Permission Sets and Profiles about your application functionality, enter Custom Permissions!
CustomPermissions
CustomPermission
NOTE: That you can also define dependencies between your Custom Permissions, for example Clear History and Reset permissions might be dependent on a Manage Important Process  custom permission in your package.
Once these have been created, you can reference them in your packaged Permission Sets and since they are packaged themselves, they can also be referenced by admins managing your application in a subscriber org.
SetCustomPermissions
The next step is to make your code react to these custom permissions being assigned or not.

New Global Variable $Permission

You can use the $Permission from a Visualforce page or as SFDCWizard points out here from Validation Rules! Here is the Visualforce page example given by Salesforce in their documentation.
1
2
3
<apex:pageBlock rendered="{!$Permission.canSeeExecutiveData}">
   <!-- Executive Data Here -->
</apex:pageBlock>

Referencing Custom Permissions from Apex

In the case of object and field level permissions, the Apex Describe API can be used to determine if an object or field is available and for what purpose, read or edit for example. This is not going help us here, as custom permissions are not related to any specific object or field. The solution is to leverage the Permission Set Object API to query theSetupEntityAccess and CustomPermission records for Permission Sets or Profiles that are assigned to the current user.
The following SOQL snippets are from the CustomPermissionsReader class i created to help with reading Custom Permissions in Apex (more on this later). As you can see you need to run two SOQL statements to get what you need. The first to get the Id’s the second to query if the user actually has been assigned a Permission Set with them in.
1
2
3
4
5
6
7
8
9
10
11
12
List<CustomPermission> customPermissions =
    [SELECT Id, DeveloperName
       FROM CustomPermission
       WHERE NamespacePrefix = :namespacePrefix];
 
List<SetupEntityAccess> setupEntities =
    [SELECT SetupEntityId
       FROM SetupEntityAccess
       WHERE SetupEntityId in :customPermissionNamesById.keySet() AND
             ParentId IN (SELECT PermissionSetId
                FROM PermissionSetAssignment
                WHERE AssigneeId = :UserInfo.getUserId())];
Now personally i don’t find this approach that appealing for general use, firstly the Permission Set object relationships are quite hard to get your head around and secondly we get charged by the platform to determine security through the SOQL governor. As a good member of the Salesforce community I of course turned my dislike into an Idea “Native Apex support for Custom Permissions” and posted it here to recommend Salesforce include a native class for reading these, similar to Custom Labels for example.

Introducing CustomPermissionReader

In the meantime I have set about creating an Apex class to help make querying and using Custom Permissions easier. Such a class might one day be replaced if my Idea becomes a reality or maybe its internal implementation just gets improved. One things for sure, i’d much rather use it for now than seed implicit SOQL’s throughout a code base!
Its pretty straight forward to use, construct it in one of two ways, depending if you want all non-namespaced Custom Permissions or if your developing a AppExchange package, give it any one of your packaged Custom Objects and it will ensure that it only ever reads the Custom Permissions associated with your package.
You can download the code and test for CustomPermissionsReader here.
1
2
3
4
5
6
7
8
// Default constructor scope is all Custom Permissions in the default namespace
CustomPermissionsReader cpr = new CustomPermissionsReader();
Boolean hasPermissionForReset = cpr.hasPermission('Reset');
 
// Alternative constructor scope is Custom Permissions that share the
//   same namespace as the custom object
CustomPermissionsReader cpr = new CustomPermissionsReader(MyPackagedObject.SObjectType);
Boolean hasPermissionForReset = cpr.hasPermission('Reset');
Like any use of SOQL we must think in a bulkified way, indeed its likely that for average to complex peaces of functionality you may want to check at least two or more custom permissions once you get started with them. As such its not really good practice to make single queries in each case.
For this reason the CustomPermissionsReader was written to load all applicable Custom Permissions and act as kind of cache. In the next example you’ll see how i’ve leveraged the Application class concept from the Apex Enterprise Patterns conventions to make it a singleton for the duration of the Apex execution context.
Here is an example of an Apex test that creates a PermissionSet, adds the Custom Permission and assigns it to the running user to confirm the Custom Permission was granted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@IsTest
private static void testCustomPermissionAssigned() {
 
    // Create PermissionSet with Custom Permission and assign to test user
    PermissionSet ps = new PermissionSet();
    ps.Name = 'Test';
    ps.Label = 'Test';
    insert ps;
    SetupEntityAccess sea = new SetupEntityAccess();
    sea.ParentId = ps.Id;
    sea.SetupEntityId = [select Id from CustomPermission where DeveloperName = 'Reset'][0].Id;
    insert sea;
    PermissionSetAssignment psa = new PermissionSetAssignment();
    psa.AssigneeId = UserInfo.getUserId();
    psa.PermissionSetId = ps.Id;
    insert psa;
 
    // Create reader
    CustomPermissionsReader cpr = new CustomPermissionsReader();
 
    // Assert the CustomPermissionsReader confirms custom permission assigned
    System.assertEquals(true, cpr.hasPermission('Reset'));
}

Seperation of Concerns and Custom Permissions

Those of you familiar with using Apex Enterprise Patterns might be wondering where checking Custom Permission fits in terms of separation of concerns and the layers the patterns promote.
The answer is at the very least in or below the Service Layer, enforcing any kind of security is the responsibility of the Service layer and callers of it are within their rights to assume it is checked. Especially if you have chosen to expose your Service layer as your application API.
This doesn’t mean however you cannot improve your user experience by using it from within Apex Controllers,  Visualforce pages or @RemoteAction methods to control the visibility of related UI components, no point in teasing the end user!

Integrating CustomerPermissionsReader into your Application class

The following code uses the Application class concept i introduced last year and at Dreamforce 2014, which is a single place to access your application scope concepts, such as factories for selectors, domain and service class implementations (it also has a big role to play when mocking).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Application {
 
    /**
     * Expoeses typed representation of the Applications Custom Permissions
     **/
    public static final PermissionsFactory Permissions = new PermissionsFactory();
 
    /**
     * Class provides a typed representation of an Applications Custom Permissions
     **/
    public class PermissionsFactory extends CustomPermissionsReader
    {
        public Boolean Reset { get { return hasPermission('Reset'); } }
    }
}
This approach ensures their is only one instance of the CustomPermissionsReader per Apex Execution context and also through the properties it exposes gives a compiler checked way of referencing the Custom Permissions, making it easier for application developers code to access them.
1
2
3
4
if(Application.Permissions.Reset)
{
  // Do something to do with Reset...
}
Finally, as a future possibility, this approach gives a nice injection point for mocking the status of Custom Permissions in your Apex Unit tests, rather than having to go through the trouble of setting up a Permission Set and assigning it in your test code every time as shown above.

This information is extracted from http://andyinthecloud.com/ 

Why to use Database.Stateful()?

Database Stateful is interface. It is used in batch classes to maintain the state of the class across transactions i.e. if you want to use ...