Refactored permission system components

Split joint permission creation into chunks

Fixes #374
This commit is contained in:
Dan Brown 2017-04-29 22:01:43 +01:00
parent ad4642c2c4
commit 1859a4d356
No known key found for this signature in database
GPG Key ID: 46D9F943C24A2EF9
8 changed files with 147 additions and 126 deletions

View File

@ -94,17 +94,6 @@ class Entity extends Ownable
->where('action', '=', $action)->count() > 0; ->where('action', '=', $action)->count() > 0;
} }
/**
* Check if this entity has live (active) restrictions in place.
* @param $role_id
* @param $action
* @return bool
*/
public function hasActiveRestriction($role_id, $action)
{
return $this->getRawAttribute('restricted') && $this->hasRestriction($role_id, $action);
}
/** /**
* Get the entity jointPermissions this is connected to. * Get the entity jointPermissions this is connected to.
* @return \Illuminate\Database\Eloquent\Relations\MorphMany * @return \Illuminate\Database\Eloquent\Relations\MorphMany
@ -176,5 +165,11 @@ class Entity extends Ownable
*/ */
public function entityRawQuery(){return '';} public function entityRawQuery(){return '';}
/**
* Get the url of this entity
* @param $path
* @return string
*/
public function getUrl($path){return '/';}
} }

View File

@ -1,6 +1,7 @@
<?php namespace BookStack\Http\Controllers; <?php namespace BookStack\Http\Controllers;
use Activity; use Activity;
use BookStack\Book;
use BookStack\Repos\EntityRepo; use BookStack\Repos\EntityRepo;
use BookStack\Repos\UserRepo; use BookStack\Repos\UserRepo;
use BookStack\Services\ExportService; use BookStack\Services\ExportService;
@ -207,13 +208,12 @@ class BookController extends Controller
// Add activity for books // Add activity for books
foreach ($sortedBooks as $bookId) { foreach ($sortedBooks as $bookId) {
/** @var Book $updatedBook */
$updatedBook = $this->entityRepo->getById('book', $bookId); $updatedBook = $this->entityRepo->getById('book', $bookId);
$this->entityRepo->buildJointPermissionsForBook($updatedBook);
Activity::add($updatedBook, 'book_sort', $updatedBook->id); Activity::add($updatedBook, 'book_sort', $updatedBook->id);
} }
// Update permissions on changed models
if (count($updatedModels) === 0) $this->entityRepo->buildJointPermissions($updatedModels);
return redirect($book->getUrl()); return redirect($book->getUrl());
} }

View File

@ -533,11 +533,11 @@ class EntityRepo
/** /**
* Alias method to update the book jointPermissions in the PermissionService. * Alias method to update the book jointPermissions in the PermissionService.
* @param Collection $collection collection on entities * @param Book $book
*/ */
public function buildJointPermissions(Collection $collection) public function buildJointPermissionsForBook(Book $book)
{ {
$this->permissionService->buildJointPermissionsForEntities($collection); $this->permissionService->buildJointPermissionsForEntity($book);
} }
/** /**

View File

@ -3,6 +3,7 @@
use BookStack\Book; use BookStack\Book;
use BookStack\Chapter; use BookStack\Chapter;
use BookStack\Entity; use BookStack\Entity;
use BookStack\EntityPermission;
use BookStack\JointPermission; use BookStack\JointPermission;
use BookStack\Ownable; use BookStack\Ownable;
use BookStack\Page; use BookStack\Page;
@ -11,6 +12,7 @@ use BookStack\User;
use Illuminate\Database\Connection; use Illuminate\Database\Connection;
use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection; use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
class PermissionService class PermissionService
{ {
@ -28,22 +30,25 @@ class PermissionService
protected $jointPermission; protected $jointPermission;
protected $role; protected $role;
protected $entityPermission;
protected $entityCache; protected $entityCache;
/** /**
* PermissionService constructor. * PermissionService constructor.
* @param JointPermission $jointPermission * @param JointPermission $jointPermission
* @param EntityPermission $entityPermission
* @param Connection $db * @param Connection $db
* @param Book $book * @param Book $book
* @param Chapter $chapter * @param Chapter $chapter
* @param Page $page * @param Page $page
* @param Role $role * @param Role $role
*/ */
public function __construct(JointPermission $jointPermission, Connection $db, Book $book, Chapter $chapter, Page $page, Role $role) public function __construct(JointPermission $jointPermission, EntityPermission $entityPermission, Connection $db, Book $book, Chapter $chapter, Page $page, Role $role)
{ {
$this->db = $db; $this->db = $db;
$this->jointPermission = $jointPermission; $this->jointPermission = $jointPermission;
$this->entityPermission = $entityPermission;
$this->role = $role; $this->role = $role;
$this->book = $book; $this->book = $book;
$this->chapter = $chapter; $this->chapter = $chapter;
@ -136,19 +141,31 @@ class PermissionService
$roles = $this->role->with('permissions')->get(); $roles = $this->role->with('permissions')->get();
// Chunk through all books // Chunk through all books
$this->book->with('permissions')->chunk(500, function ($books) use ($roles) { $this->book->newQuery()->with('chapters', 'pages')->chunk(5, function ($books) use ($roles) {
$this->createManyJointPermissions($books, $roles); $this->buildJointPermissionsForBooks($books, $roles);
}); });
}
// Chunk through all chapters /**
$this->chapter->with('book', 'permissions')->chunk(500, function ($chapters) use ($roles) { * Build joint permissions for an array of books
$this->createManyJointPermissions($chapters, $roles); * @param Collection $books
}); * @param Collection $roles
* @param bool $deleteOld
*/
protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false) {
$entities = clone $books;
// Chunk through all pages foreach ($books as $book) {
$this->page->with('book', 'chapter', 'permissions')->chunk(500, function ($pages) use ($roles) { foreach ($book->chapters as $chapter) {
$this->createManyJointPermissions($pages, $roles); $entities->push($chapter);
}); }
foreach ($book->pages as $page) {
$entities->push($page);
}
}
if ($deleteOld) $this->deleteManyJointPermissionsForEntities($entities->all());
$this->createManyJointPermissions($entities, $roles);
} }
/** /**
@ -157,18 +174,9 @@ class PermissionService
*/ */
public function buildJointPermissionsForEntity(Entity $entity) public function buildJointPermissionsForEntity(Entity $entity)
{ {
$roles = $this->role->get(); $roles = $this->role->newQuery()->get();
$entities = collect([$entity]); $book = ($entity->isA('book')) ? $entity : $entity->book;
$this->buildJointPermissionsForBooks(collect([$book]), $roles, true);
if ($entity->isA('book')) {
$entities = $entities->merge($entity->chapters);
$entities = $entities->merge($entity->pages);
} elseif ($entity->isA('chapter')) {
$entities = $entities->merge($entity->pages);
}
$this->deleteManyJointPermissionsForEntities($entities);
$this->createManyJointPermissions($entities, $roles);
} }
/** /**
@ -178,7 +186,7 @@ class PermissionService
public function buildJointPermissionsForEntities(Collection $entities) public function buildJointPermissionsForEntities(Collection $entities)
{ {
$roles = $this->role->get(); $roles = $this->role->get();
$this->deleteManyJointPermissionsForEntities($entities); $this->deleteManyJointPermissionsForEntities($entities->all());
$this->createManyJointPermissions($entities, $roles); $this->createManyJointPermissions($entities, $roles);
} }
@ -193,18 +201,8 @@ class PermissionService
$this->deleteManyJointPermissionsForRoles($roles); $this->deleteManyJointPermissionsForRoles($roles);
// Chunk through all books // Chunk through all books
$this->book->with('permissions')->chunk(500, function ($books) use ($roles) { $this->book->with('chapters', 'pages')->chunk(5, function ($books) use ($roles) {
$this->createManyJointPermissions($books, $roles); $this->buildJointPermissionsForBooks($books, $roles);
});
// Chunk through all chapters
$this->chapter->with('book', 'permissions')->chunk(500, function ($books) use ($roles) {
$this->createManyJointPermissions($books, $roles);
});
// Chunk through all pages
$this->page->with('book', 'chapter', 'permissions')->chunk(500, function ($books) use ($roles) {
$this->createManyJointPermissions($books, $roles);
}); });
} }
@ -245,12 +243,14 @@ class PermissionService
{ {
if (count($entities) === 0) return; if (count($entities) === 0) return;
$query = $this->jointPermission->newQuery(); $query = $this->jointPermission->newQuery();
foreach ($entities as $entity) {
$query->orWhere(function($query) use ($entity) { foreach ($entities as $entity) {
$query->where('entity_id', '=', $entity->id) $query->orWhere(function($query) use ($entity) {
->where('entity_type', '=', $entity->getMorphClass()); $query->where('entity_id', '=', $entity->id)
}); ->where('entity_type', '=', $entity->getMorphClass());
} });
}
$query->delete(); $query->delete();
} }
@ -263,34 +263,59 @@ class PermissionService
{ {
$this->readyEntityCache(); $this->readyEntityCache();
$jointPermissions = []; $jointPermissions = [];
// Fetch Entity Permissions and create a mapping of entity restricted statuses
$entityRestrictedMap = [];
$permissionFetch = $this->entityPermission->newQuery();
foreach ($entities as $entity) {
$entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
$permissionFetch->orWhere(function($query) use ($entity) {
$query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
});
}
$permissions = $permissionFetch->get();
// Create a mapping of explicit entity permissions
$permissionMap = [];
foreach ($permissions as $permission) {
$key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
$isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
$permissionMap[$key] = $isRestricted;
}
// Create a mapping of role permissions
$rolePermissionMap = [];
foreach ($roles as $role) {
foreach ($role->getRelationValue('permissions') as $permission) {
$rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
}
}
// Create Joint Permission Data
foreach ($entities as $entity) { foreach ($entities as $entity) {
foreach ($roles as $role) { foreach ($roles as $role) {
foreach ($this->getActions($entity) as $action) { foreach ($this->getActions($entity) as $action) {
$jointPermissions[] = $this->createJointPermissionData($entity, $role, $action); $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
} }
} }
} }
$this->jointPermission->insert($jointPermissions); foreach (array_chunk($jointPermissions, 5000) as $jointPermissionChunk) {
$this->jointPermission->insert($jointPermissionChunk);
}
} }
/** /**
* Get the actions related to an entity. * Get the actions related to an entity.
* @param $entity * @param Entity $entity
* @return array * @return array
*/ */
protected function getActions($entity) protected function getActions(Entity $entity)
{ {
$baseActions = ['view', 'update', 'delete']; $baseActions = ['view', 'update', 'delete'];
if ($entity->isA('chapter') || $entity->isA('book')) $baseActions[] = 'page-create';
if ($entity->isA('chapter')) { if ($entity->isA('book')) $baseActions[] = 'chapter-create';
$baseActions[] = 'page-create'; return $baseActions;
} else if ($entity->isA('book')) {
$baseActions[] = 'page-create';
$baseActions[] = 'chapter-create';
}
return $baseActions;
} }
/** /**
@ -298,14 +323,16 @@ class PermissionService
* for a particular action. * for a particular action.
* @param Entity $entity * @param Entity $entity
* @param Role $role * @param Role $role
* @param $action * @param string $action
* @param array $permissionMap
* @param array $rolePermissionMap
* @return array * @return array
*/ */
protected function createJointPermissionData(Entity $entity, Role $role, $action) protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
{ {
$permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action; $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
$roleHasPermission = $role->hasPermission($permissionPrefix . '-all'); $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
$roleHasPermissionOwn = $role->hasPermission($permissionPrefix . '-own'); $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
$explodedAction = explode('-', $action); $explodedAction = explode('-', $action);
$restrictionAction = end($explodedAction); $restrictionAction = end($explodedAction);
@ -313,54 +340,46 @@ class PermissionService
return $this->createJointPermissionDataArray($entity, $role, $action, true, true); return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
} }
if ($entity->isA('book')) { if ($entity->restricted) {
$hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
if (!$entity->restricted) { return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
} else {
$hasAccess = $entity->hasActiveRestriction($role->id, $restrictionAction);
return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
}
} elseif ($entity->isA('chapter')) {
if (!$entity->restricted) {
$book = $this->getBook($entity->book_id);
$hasExplicitAccessToBook = $book->hasActiveRestriction($role->id, $restrictionAction);
$hasPermissiveAccessToBook = !$book->restricted;
return $this->createJointPermissionDataArray($entity, $role, $action,
($hasExplicitAccessToBook || ($roleHasPermission && $hasPermissiveAccessToBook)),
($hasExplicitAccessToBook || ($roleHasPermissionOwn && $hasPermissiveAccessToBook)));
} else {
$hasAccess = $entity->hasActiveRestriction($role->id, $restrictionAction);
return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
}
} elseif ($entity->isA('page')) {
if (!$entity->restricted) {
$book = $this->getBook($entity->book_id);
$hasExplicitAccessToBook = $book->hasActiveRestriction($role->id, $restrictionAction);
$hasPermissiveAccessToBook = !$book->restricted;
$chapter = $this->getChapter($entity->chapter_id);
$hasExplicitAccessToChapter = $chapter && $chapter->hasActiveRestriction($role->id, $restrictionAction);
$hasPermissiveAccessToChapter = $chapter && !$chapter->restricted;
$acknowledgeChapter = ($chapter && $chapter->restricted);
$hasExplicitAccessToParents = $acknowledgeChapter ? $hasExplicitAccessToChapter : $hasExplicitAccessToBook;
$hasPermissiveAccessToParents = $acknowledgeChapter ? $hasPermissiveAccessToChapter : $hasPermissiveAccessToBook;
return $this->createJointPermissionDataArray($entity, $role, $action,
($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
);
} else {
$hasAccess = $entity->hasRestriction($role->id, $action);
return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
}
} }
if ($entity->isA('book')) {
return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
}
// For chapters and pages, Check if explicit permissions are set on the Book.
$book = $this->getBook($entity->book_id);
$hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
$hasPermissiveAccessToParents = !$book->restricted;
// For pages with a chapter, Check if explicit permissions are set on the Chapter
if ($entity->isA('page') && $entity->chapter_id !== 0) {
$chapter = $this->getChapter($entity->chapter_id);
$hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
if ($chapter->restricted) {
$hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
}
}
return $this->createJointPermissionDataArray($entity, $role, $action,
($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
);
}
/**
* Check for an active restriction in an entity map.
* @param $entityMap
* @param Entity $entity
* @param Role $role
* @param $action
* @return bool
*/
protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action) {
$key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
return isset($entityMap[$key]) ? $entityMap[$key] : false;
} }
/** /**
@ -375,11 +394,10 @@ class PermissionService
*/ */
protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn) protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
{ {
$entityClass = get_class($entity);
return [ return [
'role_id' => $role->getRawAttribute('id'), 'role_id' => $role->getRawAttribute('id'),
'entity_id' => $entity->getRawAttribute('id'), 'entity_id' => $entity->getRawAttribute('id'),
'entity_type' => $entityClass, 'entity_type' => $entity->getMorphClass(),
'action' => $action, 'action' => $action,
'has_permission' => $permissionAll, 'has_permission' => $permissionAll,
'has_permission_own' => $permissionOwn, 'has_permission_own' => $permissionOwn,

View File

@ -28,6 +28,12 @@ class DummyContentSeeder extends Seeder
$book->pages()->saveMany($pages); $book->pages()->saveMany($pages);
}); });
$largeBook = factory(\BookStack\Book::class)->create(['name' => 'Large book' . str_random(10), 'created_by' => $user->id, 'updated_by' => $user->id]);
$pages = factory(\BookStack\Page::class, 200)->make(['created_by' => $user->id, 'updated_by' => $user->id]);
$chapters = factory(\BookStack\Chapter::class, 50)->make(['created_by' => $user->id, 'updated_by' => $user->id]);
$largeBook->pages()->saveMany($pages);
$largeBook->chapters()->saveMany($chapters);
app(\BookStack\Services\PermissionService::class)->buildJointPermissions(); app(\BookStack\Services\PermissionService::class)->buildJointPermissions();
app(\BookStack\Services\SearchService::class)->indexAllEntities(); app(\BookStack\Services\SearchService::class)->indexAllEntities();
} }

View File

@ -42,7 +42,7 @@ class EntitySearchTest extends TestCase
public function test_book_search() public function test_book_search()
{ {
$book = \BookStack\Book::all()->first(); $book = \BookStack\Book::first();
$page = $book->pages->last(); $page = $book->pages->last();
$chapter = $book->chapters->last(); $chapter = $book->chapters->last();

View File

@ -1,5 +1,6 @@
<?php namespace Tests; <?php namespace Tests;
use BookStack\Role;
use BookStack\Tag; use BookStack\Tag;
use BookStack\Page; use BookStack\Page;
use BookStack\Services\PermissionService; use BookStack\Services\PermissionService;

View File

@ -226,6 +226,7 @@ class RestrictionsTest extends BrowserKitTest
->type('test content', 'html') ->type('test content', 'html')
->press('Save Page') ->press('Save Page')
->seePageIs($chapter->book->getUrl() . '/page/test-page'); ->seePageIs($chapter->book->getUrl() . '/page/test-page');
$this->visit($chapterUrl)->seeInElement('.action-buttons', 'New Page'); $this->visit($chapterUrl)->seeInElement('.action-buttons', 'New Page');
} }