We need to manage access to files from within apex code (triggers mostly).
In general, we need to allow only specific users (not profiles) read access on a per-file basis. As in, on our page a user (using a Customer Community user profile) can pick and choose which users (also community users) have access to which files.
From what I've learned, this should be doable on the ContentDocumentLink object, but that doesn't seem to work. Even if the visibility field is set to InternalUsers community users can access the files.
To ask another way:
I would like to replicate the process of point-'n-click sharing on files, but in apex code.
If I go to a chatter file I can manage the sharing. Visible only to me (the owner) or a few of my friends and so on.
So what happens when I do that? What fields on which objects are being changed? How can I replicate that in code?

EDIT: Additional data has come to light.
Thanks to Pranay's answer I now know where to look. However, we still seem to be having a problem. What follows is our process.
Send BLOB to Salesforce, create a ContentVersion (using Salesforce REST services).
Salesforce then creates a ContentDocument for that ContentVersion.
Salesforce then creates a ContentDocumentLink linking that document to the user that created it.
By default, at this stage only the user can see this file, and any user that has See All Files or Modify All Files permission (set in profile).
However, when linking the file to an object record (custom or standard) (essentially creating another ContentDocumentLink), all users can now view the file.
We need to be able to link the file to a custom object, and still maintain that very few users be able to view the file (or download from a direct download link).


1 Answer 1


This might get a bit confusing but would try to answer to the best of my knowledge.

Whenever you upload a file, you are actually creating a record of ContentVersion. That content version is just file, without linkage to any record, user.

Inserting ContentVersion automatically creates a record of ContentDocument. As you can upload multiple versions of file, ContentDocument will always point to the latest version of the file uploaded.

How is file sharing handled?

Well its handled by another junction object. ContentDocumentLink. ContentDocumentLink object has 2 lookup fields, 1 to link ContentDocument and Other to link shared entity(User/Group etc)

enter image description here

So from Salesforce UI whenever you share a file, you are inserting a record of ContentDocumentLink into the database. Thus if you can create those records via Apex in certain triggger it would suit your job.

Source: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_contentdocumentlink.htm



Source: https://help.salesforce.com/articleView?id=collab_files_overview.htm&type=5


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .