Skip to content

Commit

Permalink
Merge pull request #72 from ubc-web-services/private_file_access_perm
Browse files Browse the repository at this point in the history
Add permission and check permission before serving private file
  • Loading branch information
occupant authored Jan 2, 2024
2 parents 7fe7278 + 436c209 commit 4a7700e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
35 changes: 35 additions & 0 deletions ubc_media_entities/ubc_media_entities.module
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();
}
6 changes: 5 additions & 1 deletion ubc_media_entities/ubc_media_entities.permissions.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
access private files:
title: 'Access private files'
description: 'View privately stored files from their direct URL path'
restrict access: TRUE
create file media:
title: 'File: Create new media'
description: ''
Expand Down Expand Up @@ -57,4 +61,4 @@ edit own private_file media:
edit own svg_icon media:
title: 'Svg Icon: Edit own media'
description: ''
restrict access: TRUE
restrict access: TRUE

0 comments on commit 4a7700e

Please sign in to comment.