3 namespace Drupal\Tests\file\Kernel;
5 use Drupal\file\Entity\File;
6 use Drupal\KernelTests\KernelTestBase;
7 use Drupal\user\Entity\User;
10 * Tests for the File access control.
14 class AccessTest extends KernelTestBase {
21 public static $modules = ['file', 'system', 'user'];
24 * An authenticated user.
26 * @var \Drupal\user\UserInterface
31 * An authenticated user.
33 * @var \Drupal\user\UserInterface
38 * The file object used in the test.
40 * @var \Drupal\file\FileInterface
47 protected function setUp() {
50 $this->installEntitySchema('file');
51 $this->installEntitySchema('user');
52 $this->installSchema('file', ['file_usage']);
53 $this->installSchema('system', 'sequences');
55 $this->user1 = User::create([
61 $this->user2 = User::create([
67 $this->file = File::create([
68 'uid' => $this->user1->id(),
69 'filename' => 'druplicon.txt',
70 'filemime' => 'text/plain',
75 * Tests that only the file owner can delete or update a file.
77 public function testOnlyOwnerCanDeleteUpdateFile() {
78 \Drupal::currentUser()->setAccount($this->user2);
79 $this->assertFalse($this->file->access('delete'));
80 $this->assertFalse($this->file->access('update'));
82 \Drupal::currentUser()->setAccount($this->user1);
83 $this->assertTrue($this->file->access('delete'));
84 $this->assertTrue($this->file->access('update'));
88 * Tests file entity field access.
90 * @see \Drupal\file\FileAccessControlHandler::checkFieldAccess()
92 public function testCheckFieldAccess() {
93 \Drupal::currentUser()->setAccount($this->user1);
94 /** @var \Drupal\file\FileInterface $file */
95 $file = File::create([
96 'uri' => 'public://test.png'
98 // While creating a file entity access will be allowed for create-only
100 $this->assertTrue($file->get('uri')->access('edit'));
101 $this->assertTrue($file->get('filemime')->access('edit'));
102 $this->assertTrue($file->get('filesize')->access('edit'));
103 // Access to the status field is denied whilst creating a file entity.
104 $this->assertFalse($file->get('status')->access('edit'));
106 // After saving the entity is no longer new and, therefore, access to
107 // create-only fields and the status field will be denied.
108 $this->assertFalse($file->get('uri')->access('edit'));
109 $this->assertFalse($file->get('filemime')->access('edit'));
110 $this->assertFalse($file->get('filesize')->access('edit'));
111 $this->assertFalse($file->get('status')->access('edit'));
115 * Tests create access checks.
117 public function testCreateAccess() {
118 // Anonymous users can create a file by default.
119 $this->assertFalse($this->file->access('create'));
121 // Authenticated users can create a file by default.
122 \Drupal::currentUser()->setAccount($this->user1);
123 $this->assertFalse($this->file->access('create'));