-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #72 from ubc-web-services/private_file_access_perm
Add permission and check permission before serving private file
- Loading branch information
Showing
2 changed files
with
40 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
<?php | ||
|
||
use Drupal\Core\StreamWrapper\StreamWrapperManager; | ||
use Drupal\user\Entity\Role; | ||
|
||
/** | ||
* Implements hook_file_download(). | ||
* https://www.chapterthree.com/blog/drupal-8-9-media-entities-private-files-and-broken-access-control | ||
*/ | ||
function ubc_media_entities_file_download($uri) { | ||
# Check if the file is coming from the private stream wrapper | ||
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; | ||
} | ||
|
||
/** | ||
* Implements hook_post_update_() to add permission to view private files | ||
*/ | ||
function ubc_media_entities_post_update_grant_private_file_permission() { | ||
$role_object = Role::load('authenticated'); | ||
$role_object->grantPermission('access private files'); | ||
$role_object->save(); | ||
} |
This file contains 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