function FileManagedAccessTest::testFileAccess

Same name and namespace in other branches
  1. 9 core/modules/file/tests/src/Kernel/FileManagedAccessTest.php \Drupal\Tests\file\Kernel\FileManagedAccessTest::testFileAccess()
  2. 8.9.x core/modules/file/tests/src/Kernel/FileManagedAccessTest.php \Drupal\Tests\file\Kernel\FileManagedAccessTest::testFileAccess()
  3. 11.x core/modules/file/tests/src/Kernel/FileManagedAccessTest.php \Drupal\Tests\file\Kernel\FileManagedAccessTest::testFileAccess()

Tests if public file is always accessible.

File

core/modules/file/tests/src/Kernel/FileManagedAccessTest.php, line 35

Class

FileManagedAccessTest
Tests access to managed files.

Namespace

Drupal\Tests\file\Kernel

Code

public function testFileAccess() : void {
  $this->installEntitySchema('user');
  $this->installEntitySchema('file');
  $this->installSchema('file', [
    'file_usage',
  ]);
  $this->installConfig('user');
  $anonymous = User::create([
    'uid' => 0,
    'name' => '',
  ]);
  $anonymous->save();
  user_role_grant_permissions(AccountInterface::ANONYMOUS_ROLE, [
    'access content',
  ]);
  // Create an authenticated user to check file access.
  $account = $this->createUser([
    'access site reports',
    'access content',
  ], NULL, FALSE, [
    'uid' => 2,
  ]);
  // Create a new file entity in the public:// stream wrapper.
  $file_public = File::create([
    'uid' => 1,
    'filename' => 'drupal.txt',
    'uri' => 'public://drupal.txt',
    'status' => FileInterface::STATUS_PERMANENT,
  ]);
  $file_public->save();
  $this->assertTrue($file_public->access('view', $account));
  $this->assertTrue($file_public->access('download', $account));
  $this->assertTrue($file_public->access('view', $anonymous));
  $this->assertTrue($file_public->access('download', $anonymous));
  // Create a new file entity in the private:// stream wrapper.
  $file_private = File::create([
    'uid' => 1,
    'filename' => 'drupal.txt',
    'uri' => 'private://drupal.txt',
    'status' => FileInterface::STATUS_PERMANENT,
  ]);
  $file_private->save();
  $this->assertFalse($file_private->access('view', $account));
  $this->assertFalse($file_private->access('download', $account));
  $this->assertFalse($file_private->access('view', $anonymous));
  $this->assertFalse($file_private->access('download', $anonymous));
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.