3 namespace BookStack\Auth\Permissions;
5 use BookStack\Auth\Role;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\BookChild;
8 use BookStack\Entities\Models\Bookshelf;
9 use BookStack\Entities\Models\Chapter;
10 use BookStack\Entities\Models\Entity;
11 use BookStack\Entities\Models\Page;
12 use Illuminate\Database\Eloquent\Builder;
13 use Illuminate\Database\Eloquent\Collection as EloquentCollection;
14 use Illuminate\Support\Facades\DB;
16 class JointPermissionBuilder
19 * @var array<string, array<int, Entity>>
21 protected $entityCache;
24 * Prepare the local entity cache and ensure it's empty.
26 * @param Entity[] $entities
28 protected function readyEntityCache(array $entities = [])
30 $this->entityCache = [];
32 foreach ($entities as $entity) {
33 $class = get_class($entity);
35 if (!isset($this->entityCache[$class])) {
36 $this->entityCache[$class] = [];
39 $this->entityCache[$class][$entity->getRawAttribute('id')] = $entity;
44 * Get a book via ID, Checks local cache.
46 protected function getBook(int $bookId): ?Book
48 if ($this->entityCache[Book::class][$bookId] ?? false) {
49 return $this->entityCache[Book::class][$bookId];
52 return Book::query()->withTrashed()->find($bookId);
56 * Get a chapter via ID, Checks local cache.
58 protected function getChapter(int $chapterId): ?Chapter
60 if ($this->entityCache[Chapter::class][$chapterId] ?? false) {
61 return $this->entityCache[Chapter::class][$chapterId];
64 return Chapter::query()
70 * Re-generate all entity permission from scratch.
72 public function buildJointPermissions()
74 JointPermission::query()->truncate();
75 $this->readyEntityCache();
77 // Get all roles (Should be the most limited dimension)
78 $roles = Role::query()->with('permissions')->get()->all();
80 // Chunk through all books
81 $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
82 $this->buildJointPermissionsForBooks($books, $roles);
85 // Chunk through all bookshelves
86 Bookshelf::query()->withTrashed()->select(['id', 'restricted', 'owned_by'])
87 ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
88 $this->buildJointPermissionsForShelves($shelves, $roles);
93 * Get a query for fetching a book with it's children.
95 protected function bookFetchQuery(): Builder
97 return Book::query()->withTrashed()
98 ->select(['id', 'restricted', 'owned_by'])->with([
99 'chapters' => function ($query) {
100 $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id']);
102 'pages' => function ($query) {
103 $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']);
109 * Build joint permissions for the given shelf and role combinations.
113 protected function buildJointPermissionsForShelves(EloquentCollection $shelves, array $roles, bool $deleteOld = false)
116 $this->deleteManyJointPermissionsForEntities($shelves->all());
118 $this->createManyJointPermissions($shelves->all(), $roles);
122 * Build joint permissions for the given book and role combinations.
126 protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
128 $entities = clone $books;
130 /** @var Book $book */
131 foreach ($books->all() as $book) {
132 foreach ($book->getRelation('chapters') as $chapter) {
133 $entities->push($chapter);
135 foreach ($book->getRelation('pages') as $page) {
136 $entities->push($page);
141 $this->deleteManyJointPermissionsForEntities($entities->all());
144 $this->createManyJointPermissions($entities->all(), $roles);
148 * Rebuild the entity jointPermissions for a particular entity.
152 public function buildJointPermissionsForEntity(Entity $entity)
154 $entities = [$entity];
155 if ($entity instanceof Book) {
156 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
157 $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
162 /** @var BookChild $entity */
164 $entities[] = $entity->book;
167 if ($entity instanceof Page && $entity->chapter_id) {
168 $entities[] = $entity->chapter;
171 if ($entity instanceof Chapter) {
172 foreach ($entity->pages as $page) {
177 $this->buildJointPermissionsForEntities($entities);
181 * Rebuild the entity jointPermissions for a collection of entities.
185 protected function buildJointPermissionsForEntities(array $entities)
187 $roles = Role::query()->get()->values()->all();
188 $this->deleteManyJointPermissionsForEntities($entities);
189 $this->createManyJointPermissions($entities, $roles);
193 * Build the entity jointPermissions for a particular role.
195 public function buildJointPermissionForRole(Role $role)
198 $role->jointPermissions()->delete();
200 // Chunk through all books
201 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
202 $this->buildJointPermissionsForBooks($books, $roles);
205 // Chunk through all bookshelves
206 Bookshelf::query()->select(['id', 'restricted', 'owned_by'])
207 ->chunk(50, function ($shelves) use ($roles) {
208 $this->buildJointPermissionsForShelves($shelves, $roles);
213 * Delete all the entity jointPermissions for a list of entities.
215 * @param Entity[] $entities
219 protected function deleteManyJointPermissionsForEntities(array $entities)
221 $idsByType = $this->entitiesToTypeIdMap($entities);
223 DB::transaction(function () use ($idsByType) {
224 foreach ($idsByType as $type => $ids) {
225 foreach (array_chunk($ids, 1000) as $idChunk) {
226 DB::table('joint_permissions')
227 ->where('entity_type', '=', $type)
228 ->whereIn('entity_id', $idChunk)
236 * Create & Save entity jointPermissions for many entities and roles.
238 * @param Entity[] $entities
239 * @param Role[] $roles
243 protected function createManyJointPermissions(array $entities, array $roles)
245 $this->readyEntityCache($entities);
246 $jointPermissions = [];
248 // Create a mapping of entity restricted statuses
249 $entityRestrictedMap = [];
250 foreach ($entities as $entity) {
251 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->getRawAttribute('id')] = boolval($entity->getRawAttribute('restricted'));
254 // Fetch related entity permissions
255 $permissions = $this->getEntityPermissionsForEntities($entities);
257 // Create a mapping of explicit entity permissions
259 foreach ($permissions as $permission) {
260 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
261 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
262 $permissionMap[$key] = $isRestricted;
265 // Create a mapping of role permissions
266 $rolePermissionMap = [];
267 foreach ($roles as $role) {
268 foreach ($role->permissions as $permission) {
269 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
273 // Create Joint Permission Data
274 foreach ($entities as $entity) {
275 foreach ($roles as $role) {
276 foreach ($this->getActions($entity) as $action) {
277 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
282 DB::transaction(function () use ($jointPermissions) {
283 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
284 DB::table('joint_permissions')->insert($jointPermissionChunk);
290 * From the given entity list, provide back a mapping of entity types to
291 * the ids of that given type. The type used is the DB morph class.
292 * @param Entity[] $entities
293 * @return array<string, int[]>
295 protected function entitiesToTypeIdMap(array $entities): array
299 foreach ($entities as $entity) {
300 $type = $entity->getMorphClass();
302 if (!isset($idsByType[$type])) {
303 $idsByType[$type] = [];
306 $idsByType[$type][] = $entity->getRawAttribute('id');
313 * Get the entity permissions for all the given entities
314 * @param Entity[] $entities
315 * @return EloquentCollection
317 protected function getEntityPermissionsForEntities(array $entities)
319 $idsByType = $this->entitiesToTypeIdMap($entities);
320 $permissionFetch = EntityPermission::query();
322 foreach ($idsByType as $type => $ids) {
323 $permissionFetch->orWhere(function (Builder $query) use ($type, $ids) {
324 $query->where('restrictable_type', '=', $type)->whereIn('restrictable_id', $ids);
328 return $permissionFetch->get();
332 * Get the actions related to an entity.
334 protected function getActions(Entity $entity): array
336 $baseActions = ['view', 'update', 'delete'];
337 if ($entity instanceof Chapter || $entity instanceof Book) {
338 $baseActions[] = 'page-create';
340 if ($entity instanceof Book) {
341 $baseActions[] = 'chapter-create';
348 * Create entity permission data for an entity and role
349 * for a particular action.
351 protected function createJointPermissionData(Entity $entity, Role $role, string $action, array $permissionMap, array $rolePermissionMap): array
353 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
354 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
355 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
356 $explodedAction = explode('-', $action);
357 $restrictionAction = end($explodedAction);
359 if ($role->system_name === 'admin') {
360 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
363 if ($entity->restricted) {
364 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
366 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
369 if ($entity instanceof Book || $entity instanceof Bookshelf) {
370 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
373 // For chapters and pages, Check if explicit permissions are set on the Book.
374 $book = $this->getBook($entity->book_id);
375 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
376 $hasPermissiveAccessToParents = !$book->restricted;
378 // For pages with a chapter, Check if explicit permissions are set on the Chapter
379 if ($entity instanceof Page && intval($entity->chapter_id) !== 0) {
380 $chapter = $this->getChapter($entity->chapter_id);
381 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
382 if ($chapter->restricted) {
383 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
387 return $this->createJointPermissionDataArray(
391 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
392 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
397 * Check for an active restriction in an entity map.
399 protected function mapHasActiveRestriction(array $entityMap, Entity $entity, Role $role, string $action): bool
401 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
403 return $entityMap[$key] ?? false;
407 * Create an array of data with the information of an entity jointPermissions.
408 * Used to build data for bulk insertion.
410 protected function createJointPermissionDataArray(Entity $entity, Role $role, string $action, bool $permissionAll, bool $permissionOwn): array
414 'entity_id' => $entity->getRawAttribute('id'),
415 'entity_type' => $entity->getMorphClass(),
416 'has_permission' => $permissionAll,
417 'has_permission_own' => $permissionOwn,
418 'owned_by' => $entity->getRawAttribute('owned_by'),
419 'role_id' => $role->getRawAttribute('id'),