I have a patient object , related to Account (lookup relationship). Profile 'Standard User' doesn't have CRUD permissions on the patient object. In Account trigger, I call call 'accounthandler.cls' which has 'With Sharing'. On After Insert of account , I create a patient record and associate it to the Account , in the accounthandler.cls For users with 'Standard User' profile, I was expecting patient record won't be created, when they create an account record, since 'With Sharing' is enabled , so class shouldn't have executed in the system context. However, I see patient record is created as well as owned by that user. Any idea, why it would create a patient record?
2 Answers
'With sharing' keyword only enforce sharing rules, not CRUD/FLS.
To enforce CRUD/FLS sharing, use 'WITH SECURITY_ENFORCED' in SOQL query and check user permission using isCreateable(), isUpdateable(), etc for DML operation in the code.
-
So if a user doesn't has a CRUD at profile level, how come a record is created through apex? Commented Mar 7, 2021 at 12:51
-
Because CRUD permission is not checked, you have to explicitly check it– 87092Commented Mar 7, 2021 at 12:57
-
Apex don't check object or field permissions during DML operations, you need to do it yourself with something like describe calls and then isCreateable(), isUpdateable(), etc. Commented Mar 7, 2021 at 14:55
Most likely Your Internal Organization-Wide Sharing for Patient Object have is set to Read Only/ReadWrite, try to change it to Private as users can only read and edit their own user record
The second part we will need to check FLS in the Code Check FLS in the Code Patient.Subject.getDescribe().isCreateable()/.isAccessible()
Difference between isCreateable and isUpdatable for DescribeFieldResult?