function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
rajmohanrajmohan 

How to Enforce Object Level Permission in Apex Script

Hi,
 
My requirement is :- Whenever User tries to insert/update/delete a record from the application (interface in VF page and Apex Controller), then based on the user's profile's object level permission he should be allowed/disallowed the DML operation. If in the Object Level Permission of the user's profile, the checkbox for creating a record in custom object is unchecked and if I try to insert a record from application then Salesforce should throw an error saying the "Insufficient privilege for inserting the record in Object".
 
But since I am writing the DML statements in apex script : all Apex scripts run in system mode, and the permissions and record sharing of the current user are not taken into account. For static testMethod's there is a system method runAs (System.runAs(user Object) ) which changes the user contexts to either an existing user or a new user. All of user's permission is then enforced. But this system method can only be used in test methods. Similarly, is there any method or way to achieve my above requirement in apex script.
hisrinuhisrinu
Hi,

You need to use the with sharing keyword for the class, then it will execute in the user mode instead of system mode.
use the following link to get more info on with sharing.

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_keywords_sharing.htm
rajmohanrajmohan
Hi,
 
Thanks for the reply.
 
I have used the keyword with sharing , please have a look at the below code:
 

public with sharing class cntrllr {

public void insertdata()

{

RBACPOC__c rbac = new RBACPOC__c();

rbac.EmpName__c = 'insert_Test4';

rbac.Address__c = 'insert_Test4';

rbac.Salary__c = 'insert_Test4';

rbac.SSN__c = 'insert_Test4';

insert rbac;

}

}

Now under: Setup - Manage Users - Profiles , I selected the profile and under Custom Object Permissions, I have unchecked the Create checkbox for RBACPOCs (which is the object name as you can see in code snippet). Now if I login with userid having this profile and I run the code , still I am able to insert record in this object. Any idea why?

Thanks and Regards,

Rajmohan

gjsgjs
With sharing only enforce sharing rules, it does not enforce a profile's object level perms (aka CRUD perms). All I can suggest is that you have a field in the custom object that is populated with a foreign key to a record that exists in your org, but for which only desired users have sharing access.