]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/JointPermissionBuilder.php
fbf77741ac43827076c3f70598a8b1afb95d72a9
[bookstack] / app / Auth / Permissions / JointPermissionBuilder.php
1 <?php
2
3 namespace BookStack\Auth\Permissions;
4
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;
15
16 class JointPermissionBuilder
17 {
18     /**
19      * @var array<string, array<int, Entity>>
20      */
21     protected $entityCache;
22
23     /**
24      * Re-generate all entity permission from scratch.
25      */
26     public function rebuildForAll()
27     {
28         JointPermission::query()->truncate();
29         $this->readyEntityCache();
30
31         // Get all roles (Should be the most limited dimension)
32         $roles = Role::query()->with('permissions')->get()->all();
33
34         // Chunk through all books
35         $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
36             $this->buildJointPermissionsForBooks($books, $roles);
37         });
38
39         // Chunk through all bookshelves
40         Bookshelf::query()->withTrashed()->select(['id', 'restricted', 'owned_by'])
41             ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
42                 $this->createManyJointPermissions($shelves->all(), $roles);
43             });
44     }
45
46     /**
47      * Rebuild the entity jointPermissions for a particular entity.
48      *
49      * @throws Throwable
50      */
51     public function rebuildForEntity(Entity $entity)
52     {
53         $entities = [$entity];
54         if ($entity instanceof Book) {
55             $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
56             $this->buildJointPermissionsForBooks($books, Role::query()->with('permissions')->get()->all(), true);
57
58             return;
59         }
60
61         /** @var BookChild $entity */
62         if ($entity->book) {
63             $entities[] = $entity->book;
64         }
65
66         if ($entity instanceof Page && $entity->chapter_id) {
67             $entities[] = $entity->chapter;
68         }
69
70         if ($entity instanceof Chapter) {
71             foreach ($entity->pages as $page) {
72                 $entities[] = $page;
73             }
74         }
75
76         $this->buildJointPermissionsForEntities($entities);
77     }
78
79     /**
80      * Build the entity jointPermissions for a particular role.
81      */
82     public function rebuildForRole(Role $role)
83     {
84         $roles = [$role];
85         $role->jointPermissions()->delete();
86
87         // Chunk through all books
88         $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
89             $this->buildJointPermissionsForBooks($books, $roles);
90         });
91
92         // Chunk through all bookshelves
93         Bookshelf::query()->select(['id', 'restricted', 'owned_by'])
94             ->chunk(50, function ($shelves) use ($roles) {
95                 $this->createManyJointPermissions($shelves->all(), $roles);
96             });
97     }
98
99     /**
100      * Prepare the local entity cache and ensure it's empty.
101      *
102      * @param Entity[] $entities
103      */
104     protected function readyEntityCache(array $entities = [])
105     {
106         $this->entityCache = [];
107
108         foreach ($entities as $entity) {
109             $class = get_class($entity);
110
111             if (!isset($this->entityCache[$class])) {
112                 $this->entityCache[$class] = [];
113             }
114
115             $this->entityCache[$class][$entity->getRawAttribute('id')] = $entity;
116         }
117     }
118
119     /**
120      * Get a book via ID, Checks local cache.
121      */
122     protected function getBook(int $bookId): ?Book
123     {
124         if ($this->entityCache[Book::class][$bookId] ?? false) {
125             return $this->entityCache[Book::class][$bookId];
126         }
127
128         return Book::query()->withTrashed()->find($bookId);
129     }
130
131     /**
132      * Get a chapter via ID, Checks local cache.
133      */
134     protected function getChapter(int $chapterId): ?Chapter
135     {
136         if ($this->entityCache[Chapter::class][$chapterId] ?? false) {
137             return $this->entityCache[Chapter::class][$chapterId];
138         }
139
140         return Chapter::query()
141             ->withTrashed()
142             ->find($chapterId);
143     }
144
145     /**
146      * Get a query for fetching a book with it's children.
147      */
148     protected function bookFetchQuery(): Builder
149     {
150         return Book::query()->withTrashed()
151             ->select(['id', 'restricted', 'owned_by'])->with([
152                 'chapters' => function ($query) {
153                     $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id']);
154                 },
155                 'pages' => function ($query) {
156                     $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']);
157                 },
158             ]);
159     }
160
161
162     /**
163      * Build joint permissions for the given book and role combinations.
164      *
165      * @throws Throwable
166      */
167     protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
168     {
169         $entities = clone $books;
170
171         /** @var Book $book */
172         foreach ($books->all() as $book) {
173             foreach ($book->getRelation('chapters') as $chapter) {
174                 $entities->push($chapter);
175             }
176             foreach ($book->getRelation('pages') as $page) {
177                 $entities->push($page);
178             }
179         }
180
181         if ($deleteOld) {
182             $this->deleteManyJointPermissionsForEntities($entities->all());
183         }
184
185         $this->createManyJointPermissions($entities->all(), $roles);
186     }
187
188     /**
189      * Rebuild the entity jointPermissions for a collection of entities.
190      *
191      * @throws Throwable
192      */
193     protected function buildJointPermissionsForEntities(array $entities)
194     {
195         $roles = Role::query()->get()->values()->all();
196         $this->deleteManyJointPermissionsForEntities($entities);
197         $this->createManyJointPermissions($entities, $roles);
198     }
199
200     /**
201      * Delete all the entity jointPermissions for a list of entities.
202      *
203      * @param Entity[] $entities
204      *
205      * @throws Throwable
206      */
207     protected function deleteManyJointPermissionsForEntities(array $entities)
208     {
209         $idsByType = $this->entitiesToTypeIdMap($entities);
210
211         DB::transaction(function () use ($idsByType) {
212             foreach ($idsByType as $type => $ids) {
213                 foreach (array_chunk($ids, 1000) as $idChunk) {
214                     DB::table('joint_permissions')
215                         ->where('entity_type', '=', $type)
216                         ->whereIn('entity_id', $idChunk)
217                         ->delete();
218                 }
219             }
220         });
221     }
222
223     /**
224      * Create & Save entity jointPermissions for many entities and roles.
225      *
226      * @param Entity[] $entities
227      * @param Role[]   $roles
228      *
229      * @throws Throwable
230      */
231     protected function createManyJointPermissions(array $entities, array $roles)
232     {
233         $this->readyEntityCache($entities);
234         $jointPermissions = [];
235
236         // Create a mapping of entity restricted statuses
237         $entityRestrictedMap = [];
238         foreach ($entities as $entity) {
239             $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->getRawAttribute('id')] = boolval($entity->getRawAttribute('restricted'));
240         }
241
242         // Fetch related entity permissions
243         $permissions = $this->getEntityPermissionsForEntities($entities);
244
245         // Create a mapping of explicit entity permissions
246         $permissionMap = [];
247         foreach ($permissions as $permission) {
248             $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
249             $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
250             $permissionMap[$key] = $isRestricted;
251         }
252
253         // Create a mapping of role permissions
254         $rolePermissionMap = [];
255         foreach ($roles as $role) {
256             foreach ($role->permissions as $permission) {
257                 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
258             }
259         }
260
261         // Create Joint Permission Data
262         foreach ($entities as $entity) {
263             foreach ($roles as $role) {
264                 foreach ($this->getActions($entity) as $action) {
265                     $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
266                 }
267             }
268         }
269
270         DB::transaction(function () use ($jointPermissions) {
271             foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
272                 DB::table('joint_permissions')->insert($jointPermissionChunk);
273             }
274         });
275     }
276
277     /**
278      * From the given entity list, provide back a mapping of entity types to
279      * the ids of that given type. The type used is the DB morph class.
280      * @param Entity[] $entities
281      * @return array<string, int[]>
282      */
283     protected function entitiesToTypeIdMap(array $entities): array
284     {
285         $idsByType = [];
286
287         foreach ($entities as $entity) {
288             $type = $entity->getMorphClass();
289
290             if (!isset($idsByType[$type])) {
291                 $idsByType[$type] = [];
292             }
293
294             $idsByType[$type][] = $entity->getRawAttribute('id');
295         }
296
297         return $idsByType;
298     }
299
300     /**
301      * Get the entity permissions for all the given entities
302      * @param Entity[] $entities
303      * @return EloquentCollection
304      */
305     protected function getEntityPermissionsForEntities(array $entities)
306     {
307         $idsByType = $this->entitiesToTypeIdMap($entities);
308         $permissionFetch = EntityPermission::query();
309
310         foreach ($idsByType as $type => $ids) {
311             $permissionFetch->orWhere(function (Builder $query) use ($type, $ids) {
312                 $query->where('restrictable_type', '=', $type)->whereIn('restrictable_id', $ids);
313             });
314         }
315
316         return $permissionFetch->get();
317     }
318
319     /**
320      * Get the actions related to an entity.
321      */
322     protected function getActions(Entity $entity): array
323     {
324         $baseActions = ['view', 'update', 'delete'];
325         if ($entity instanceof Chapter || $entity instanceof Book) {
326             $baseActions[] = 'page-create';
327         }
328         if ($entity instanceof Book) {
329             $baseActions[] = 'chapter-create';
330         }
331
332         return $baseActions;
333     }
334
335     /**
336      * Create entity permission data for an entity and role
337      * for a particular action.
338      */
339     protected function createJointPermissionData(Entity $entity, Role $role, string $action, array $permissionMap, array $rolePermissionMap): array
340     {
341         $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
342         $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
343         $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
344         $explodedAction = explode('-', $action);
345         $restrictionAction = end($explodedAction);
346
347         if ($role->system_name === 'admin') {
348             return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
349         }
350
351         if ($entity->restricted) {
352             $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
353
354             return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
355         }
356
357         if ($entity instanceof Book || $entity instanceof Bookshelf) {
358             return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
359         }
360
361         // For chapters and pages, Check if explicit permissions are set on the Book.
362         $book = $this->getBook($entity->book_id);
363         $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
364         $hasPermissiveAccessToParents = !$book->restricted;
365
366         // For pages with a chapter, Check if explicit permissions are set on the Chapter
367         if ($entity instanceof Page && intval($entity->chapter_id) !== 0) {
368             $chapter = $this->getChapter($entity->chapter_id);
369             $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
370             if ($chapter->restricted) {
371                 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
372             }
373         }
374
375         return $this->createJointPermissionDataArray(
376             $entity,
377             $role,
378             $action,
379             ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
380             ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
381         );
382     }
383
384     /**
385      * Check for an active restriction in an entity map.
386      */
387     protected function mapHasActiveRestriction(array $entityMap, Entity $entity, Role $role, string $action): bool
388     {
389         $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
390
391         return $entityMap[$key] ?? false;
392     }
393
394     /**
395      * Create an array of data with the information of an entity jointPermissions.
396      * Used to build data for bulk insertion.
397      */
398     protected function createJointPermissionDataArray(Entity $entity, Role $role, string $action, bool $permissionAll, bool $permissionOwn): array
399     {
400         return [
401             'action'             => $action,
402             'entity_id'          => $entity->getRawAttribute('id'),
403             'entity_type'        => $entity->getMorphClass(),
404             'has_permission'     => $permissionAll,
405             'has_permission_own' => $permissionOwn,
406             'owned_by'           => $entity->getRawAttribute('owned_by'),
407             'role_id'            => $role->getRawAttribute('id'),
408         ];
409     }
410
411 }