View source
<?php
namespace Drupal\Tests\file\Kernel;
use Drupal\file\Entity\File;
use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\User;
class AccessTest extends KernelTestBase {
public static $modules = [
'file',
'system',
'user',
];
protected $user1;
protected $user2;
protected $file;
protected function setUp() {
parent::setUp();
$this
->installEntitySchema('file');
$this
->installEntitySchema('user');
$this
->installSchema('file', [
'file_usage',
]);
$this
->installSchema('system', 'sequences');
$this->user1 = User::create([
'name' => 'user1',
'status' => 1,
]);
$this->user1
->save();
$this->user2 = User::create([
'name' => 'user2',
'status' => 1,
]);
$this->user2
->save();
$this->file = File::create([
'uid' => $this->user1
->id(),
'filename' => 'druplicon.txt',
'filemime' => 'text/plain',
]);
}
public function testOnlyOwnerCanDeleteUpdateFile() {
\Drupal::currentUser()
->setAccount($this->user2);
$this
->assertFalse($this->file
->access('delete'));
$this
->assertFalse($this->file
->access('update'));
\Drupal::currentUser()
->setAccount($this->user1);
$this
->assertTrue($this->file
->access('delete'));
$this
->assertTrue($this->file
->access('update'));
}
public function testCheckFieldAccess() {
\Drupal::currentUser()
->setAccount($this->user1);
$file = File::create([
'uri' => 'public://test.png',
]);
$this
->assertTrue($file
->get('uri')
->access('edit'));
$this
->assertTrue($file
->get('filemime')
->access('edit'));
$this
->assertTrue($file
->get('filesize')
->access('edit'));
$this
->assertFalse($file
->get('status')
->access('edit'));
$file
->save();
$this
->assertFalse($file
->get('uri')
->access('edit'));
$this
->assertFalse($file
->get('filemime')
->access('edit'));
$this
->assertFalse($file
->get('filesize')
->access('edit'));
$this
->assertFalse($file
->get('status')
->access('edit'));
}
public function testCreateAccess() {
$this
->assertFalse($this->file
->access('create'));
\Drupal::currentUser()
->setAccount($this->user1);
$this
->assertFalse($this->file
->access('create'));
}
public function testFileCacheability() {
$file = File::create([
'filename' => 'green-scarf',
'uri' => 'private://green-scarf',
'filemime' => 'text/plain',
'status' => FILE_STATUS_PERMANENT,
]);
$file
->save();
\Drupal::service('session')
->set('anonymous_allowed_file_ids', [
$file
->id() => $file
->id(),
]);
$account = User::getAnonymousUser();
$file
->setOwnerId($account
->id())
->save();
$this
->assertSame([
'session',
'user',
], $file
->access('view', $account, TRUE)
->getCacheContexts());
$this
->assertSame([
'session',
'user',
], $file
->access('download', $account, TRUE)
->getCacheContexts());
$account = $this->user1;
$file
->setOwnerId($account
->id())
->save();
$this
->assertSame([
'user',
], $file
->access('view', $account, TRUE)
->getCacheContexts());
$this
->assertSame([
'user',
], $file
->access('download', $account, TRUE)
->getCacheContexts());
}
}