Last active
July 16, 2025 04:49
-
-
Save paboden/f695f023fb2379dc53f3f248d07fcb49 to your computer and use it in GitHub Desktop.
Drupal 10: Apply permission check to private files from media entities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| access private files: | |
| title: 'Access private files' | |
| description: 'View privately stored files from their direct URL path' | |
| # For more information about this issue, please see https://www.drupal.org/project/drupal/issues/2984093 | |
| # and https://www.drupal.org/node/2904842. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| use Drupal\Core\StreamWrapper\StreamWrapperManager; | |
| /** | |
| * Implements hook_file_download(). | |
| * | |
| * NOTE this issue shouldnt be an issue anymore, but this can still be | |
| * useful for more detailed control or for other download manipulation. | |
| */ | |
| function MODULE_file_download($uri) { | |
| # Check if the file is coming from the private stream wrapper. | |
| # Permissions can only be controlled this way on private files. | |
| # The files are essentially stored in the db rather than in the | |
| # files directories. Those types of files require other access | |
| # control methods. | |
| if (StreamWrapperManager::getScheme($uri) == 'private') { | |
| # 1: Block anonymous users. | |
| if (Drupal::currentUser()->isAnonymous()) { | |
| return -1; | |
| } | |
| # 2: The user does not have the permission "access private files". | |
| if (!\Drupal::currentUser()->hasPermission('access private files')) { | |
| return -1; | |
| } | |
| } | |
| return NULL; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment