Thursday, December 8, 2016

Visualforce - Beyond Basics Series 9 - Quick way to check page access

What is page access ?

In salesforce, we can apply security to visualforce pages based on profiles.


How to enforce them in visualforce ?

It's is enforced automatically when user tries the access the restricted page. But, if you want to identify the access before you redirect the user, there's a solution for that.


How to do that ?

Apex profile getContent() method on PageReference class. This applies the profile permissions before returning the content. So, we could use that to determine the access.


Where is the code ?

For illustration, i have given a textbox to accept the page name & then check the access based on that.


public class testcls9_08122016 {
public string pageName { get; set; }
public Boolean getHasAccess() {
try {
PageReference newPage = new PageReference('/apex/'+pageName);
newPage.getContent();
} catch(Exception e) {
return False;
}
return True;
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
<apex:page controller="testcls9_08122016">
<apex:form>
<apex:inputText value="{!pageName}" html-placeholder="Enter page name to check access"/>
<apex:commandButton value="check" rerender="MessageArea"/>
<apex:outputPanel id="MessageArea">
<apex:outputPanel layout="block" rendered="{!HasAccess}">
Yes, Page {!pageName} has access
</apex:outputPanel>
<apex:outputPanel layout="block" rendered="{!!HasAccess}">
Sorry, You don't have Page {!pageName} access
</apex:outputPanel>
</apex:outputPanel>
</apex:form>
</apex:page>
view raw gistfile1.txt hosted with ❤ by GitHub


No comments:

Post a Comment

Thanks for reading my blog !