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
FdeBergeyckFdeBergeyck 

Limit query results depending on users' record access rights

Dear all,

 

I'm trying to build a custom visualforce search engine. My issue is that when I query on objects with apex, apex returns all valid records independently of the user access rights. Is there a way to tell apex to only query on records the user has access to?

 

If it is not possible, does anyone have an idea how I can remove from the results all Accounts that the user cannot access? I tried with the AccountShare object, but the UserOrGroupId related list is to complex to use (sharing can be done manually, through role, groups, subordinated roles, etc.).

 

Thank you for your help!

 

François

Message Edited by FdeBergeyck on 08-11-2009 12:55 AM
Rajesh ShahRajesh Shah

Did you tried using "with sharing" parameter in your apex class? The with sharing keyword directs the platform to use the security sharing permissions of the user currently logged in, rather than granting full access to all records.

 

E.g.:

public with sharing class customController {
. . .
}

 

For more details, check the Apex Language Reference.

bob_buzzardbob_buzzard
Is your controller class declared as "with sharing"?  If not, it will run as the system user and have access to everything. 
bob_buzzardbob_buzzard

Rajesh beat me to the punch!

 

The apex docs aren't clear about the exact ramifications of "with sharing", but there is this snippet that is encouraging:

 

Enforcing the current user's sharing rules can impact:

SOQL and SOSL queries. A query may return fewer rows than it would operating in system context.

FdeBergeyckFdeBergeyck

Indeed, I'm not using the 'with sharing' in the definition of my class, but that is because I make other queries in my class where I need to access all records, even the ones that the user can't access.

 

Is there a way to precise the 'with sharing' on query level instead as on class level? Or to query on all records when I've added the 'with sharing' in my class definition?

bob_buzzardbob_buzzard

You can only define the sharing behaviour at the class level.

 

I'd suggest that you put the methods that need to take the users permissions into account an inner class defined "with sharing", and leave those that you wish to run in system mode in your main class.

FdeBergeyckFdeBergeyck

Ok, that's a good idea!

 

Thank you very much for your help!!

 

Rgrds,

 

François