Imagine that you want to disable downloads for certain users based on the name of the file uploaded to Salesforce. This is totally possible thanks to the power of Apex classes. We can use the following example code inside of a new Apex class called ContentDownloadHandlerFactoryImpl
:
public class ContentDownloadHandlerFactoryImpl implements Sfc.ContentDownloadHandlerFactory {
public Sfc.ContentDownloadHandler getContentDownloadHandler(List<ID> ids, Sfc.ContentDownloadContext context) {
// See if the user has the top secret role (based on developer name field).
Boolean isTopSecret = [
SELECT Id
FROM UserRole
WHERE ID = :UserInfo.getUserRoleId()
AND DeveloperName = 'TOP_SECRET_PERSON'
].size() > 0;
// Get the list of content documents from the ids which are actually content
// version IDs.
List<ContentDocument> docs = [
SELECT Id, Title, FileType, FileExtension
FROM ContentDocument
WHERE ID IN (
SELECT ContentDocumentId
FROM ContentVersion
WHERE Id IN :ids
)
];
Sfc.ContentDownloadHandler contentDownloadHandler = new Sfc.ContentDownloadHandler();
// Loop through the documents and disable the download if any start off with
// "TOP_SECRET-" even though the user doesn't have the TOP_SECRET_PERSON
// role.
for (ContentDocument doc : docs) {
if (!isTopSecret && doc.Title.startsWith('TOP_SECRET-')) {
contentDownloadHandler.isDownloadAllowed = false;
contentDownloadHandler.downloadErrorMessage = 'You do not have permission to download this top secret file.';
return contentDownloadHandler;
}
}
contentDownloadHandler.isDownloadAllowed = true;
return contentDownloadHandler;
}
}
The above code essentially prevents files whose file name starts off with TOP_SECRET-
from being downloaded by anyone whose user role’s developer name is not TOP_SECRET_PERSON
.
Feel free to modify this code to suit your own purposes. As always, happy coding! š
1 Comment
Rajesj · May 22, 2023 at 10:00 AM
But this will work in desktop not in mobile any idea how to restrict in mobile??