Let’s say that similar to what we did in yesterday’s post, today you want to disable downloads based on a file name.
The difference is this time you want to target the user’s profile type instead of their role. Once again, using an Apex Salesforce class makes this possible. 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) {
    // The profile as a list of profiles as long as the name doesn't contain
    // "Admin".
    List<Profile> profiles = [
      SELECT Id, Name
      FROM Profile
      WHERE Id = :UserInfo.getProfileId()
        AND Name NOT LIKE '%Admin%'
    ];

    // Indicates if the user's profile is not an admin profile.
    Boolean isNotAdmin = profiles.size() > 0;

    // Get the list of the content versions.
    List<ContentVersion> cvs = [
      SELECT Id, Title
      FROM ContentVersion
      WHERE Id IN :ids
    ];
    
    Sfc.ContentDownloadHandler cdh = new Sfc.ContentDownloadHandler();
    
    // Loop through the files and see if any start with "TOP_SECRET-".  If user
    // is not an admin and the file name starts off with "TOP_SECRET-" the user
    // will not have access to download the file.
    for (ContentVersion cv : cvs) {
      if (isNotAdmin && cv.Title.startsWith('TOP_SECRET-')) {
        cdh.isDownloadAllowed = false;
        cdh.downloadErrorMessage = 'You do not have permission to download this file.';
        return cdh;
      }
    }
    
    // If at this point allow the download.
    cdh.isDownloadAllowed = true;
    return cdh;
  }
}

The code above prevents files whose name starts off with TOP_SECRET- from being downloaded by anyone whose user profile name doesn’t contain the string Admin.

Just like last time, feel free to modify this code to suit your own purposes. Happy coding! šŸ˜Ž

Categories: BlogSalesforce

Leave a Reply

Your email address will not be published. Required fields are marked *