3 namespace Drupal\Tests\file\Functional;
5 use Drupal\file\Entity\File;
6 use Drupal\user\Entity\Role;
9 * Tests access to managed files.
13 class FileManagedAccessTest extends FileManagedTestBase {
18 protected function setUp() {
21 // Give anonymous users permission to access content, so they can view and
22 // download public files.
23 $anonymous_role = Role::load(Role::ANONYMOUS_ID);
24 $anonymous_role->grantPermission('access content');
25 $anonymous_role->save();
29 * Tests if public file is always accessible.
31 public function testFileAccess() {
32 // Create a new file entity.
33 $file = File::create([
35 'filename' => 'drupal.txt',
36 'uri' => 'public://drupal.txt',
37 'filemime' => 'text/plain',
38 'status' => FILE_STATUS_PERMANENT,
40 file_put_contents($file->getFileUri(), 'hello world');
42 // Save it, inserting a new record.
45 // Create authenticated user to check file access.
46 $account = $this->createUser(['access site reports', 'access content']);
48 $this->assertTrue($file->access('view', $account), 'Public file is viewable to authenticated user');
49 $this->assertTrue($file->access('download', $account), 'Public file is downloadable to authenticated user');
51 // Create anonymous user to check file access.
52 $account = $this->createUser()->getAnonymousUser();
54 $this->assertTrue($file->access('view', $account), 'Public file is viewable to anonymous user');
55 $this->assertTrue($file->access('download', $account), 'Public file is downloadable to anonymous user');
57 // Create a new file entity.
58 $file = File::create([
60 'filename' => 'drupal.txt',
61 'uri' => 'private://drupal.txt',
62 'filemime' => 'text/plain',
63 'status' => FILE_STATUS_PERMANENT,
65 file_put_contents($file->getFileUri(), 'hello world');
67 // Save it, inserting a new record.
70 // Create authenticated user to check file access.
71 $account = $this->createUser(['access site reports', 'access content']);
73 $this->assertFalse($file->access('view', $account), 'Private file is not viewable to authenticated user');
74 $this->assertFalse($file->access('download', $account), 'Private file is not downloadable to authenticated user');
76 // Create anonymous user to check file access.
77 $account = $this->createUser()->getAnonymousUser();
79 $this->assertFalse($file->access('view', $account), 'Private file is not viewable to anonymous user');
80 $this->assertFalse($file->access('download', $account), 'Private file is not downloadable to anonymous user');