13

Salesforce Apex – Disable Downloads Based On File Name & User Role

 3 years ago
source link: https://cwestblog.com/2020/02/20/salesforce-apex-disable-downloads-based-on-file-name-and-user-role/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Salesforce Apex – Disable Downloads Based On File Name & User Role

Published by Chris West on February 20, 2020

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! 😎


Leave a Reply Cancel reply

placeholder.jpg
Name *
Email *
Website

Save my name, email, and website in this browser for the next time I comment.

five  ×   =  twenty five

What's on your mind?

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK