Search code examples
salesforceapex-codevisualforce

Salesforce: Is it a good idea to use SOQL to enforce security and limit record access?


This is more of a best practices question. Our org currently has "public read" permissions on our org wide defaults for custom objects. We cannot make this private because of the way its working now for internal employees or rather we are trying to avoid this.

I am also creating a customer portal with custom visual force pages...where I display data using SOQL queries.

Is it a good idea to add a clause on the SOQL query to return only those records where the account id matches the logged in user's acount id?

I did it and it works fine...But are there any pitfalls to this method that I am overlooking?

Thanks, Calvin


Solution

  • Per the Visualforce Documentation

    Because standard controllers execute in user mode, in which the permissions, field-level security, and sharing rules of the current user are enforced, extending a standard controller allows you to build a Visualforce page that respects user permissions. Although the extension class executes in system mode, the standard controller executes in user mode. As with custom controllers, you can specify whether a user can execute methods in a controller extension based on the user's profile.

    I believe the idea being, as long as your classes are public with sharing then permissions should be enforced and records should not be returned that the user cannot see (same with fields on a record).

    per the Apex Documentation

    Apex generally runs in system context; that is, the current user's permissions, field-level security, and sharing rules aren’t taken into account during code execution.

    Use the with sharing keywords when declaring a class to enforce the sharing rules that apply to the current user. For example:

    public with sharing class sharingClass {
    
    // Code here 
    
    
    }
    

    Use the without sharing keywords when declaring a class to ensure that the sharing rules for the current user are not enforced. For example:

    public without sharing class noSharing {
    
    // Code here 
    
    
    }
    

    Otherwise you would have to spend hours ensuring that the right permissions applied at exactly the right time for the right user. It would almost completely defeat the purpose of a visualforce page!