]> BookStack Code Mirror - bookstack/blob - app/Auth/Permissions/JointPermissionBuilder.php
c87560fe043cf176008c10e4145ed1001fc291f8
[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      * Prepare the local entity cache and ensure it's empty.
25      *
26      * @param Entity[] $entities
27      */
28     protected function readyEntityCache(array $entities = [])
29     {
30         $this->entityCache = [];
31
32         foreach ($entities as $entity) {
33             $class = get_class($entity);
34
35             if (!isset($this->entityCache[$class])) {
36                 $this->entityCache[$class] = [];
37             }
38
39             $this->entityCache[$class][$entity->getRawAttribute('id')] = $entity;
40         }
41     }
42
43     /**
44      * Get a book via ID, Checks local cache.
45      */
46     protected function getBook(int $bookId): ?Book
47     {
48         if ($this->entityCache[Book::class][$bookId] ?? false) {
49             return $this->entityCache[Book::class][$bookId];
50         }
51
52         return Book::query()->withTrashed()->find($bookId);
53     }
54
55     /**
56      * Get a chapter via ID, Checks local cache.
57      */
58     protected function getChapter(int $chapterId): ?Chapter
59     {
60         if ($this->entityCache[Chapter::class][$chapterId] ?? false) {
61             return $this->entityCache[Chapter::class][$chapterId];
62         }
63
64         return Chapter::query()
65             ->withTrashed()
66             ->find($chapterId);
67     }
68
69     /**
70      * Re-generate all entity permission from scratch.
71      */
72     public function buildJointPermissions()
73     {
74         JointPermission::query()->truncate();
75         $this->readyEntityCache();
76
77         // Get all roles (Should be the most limited dimension)
78         $roles = Role::query()->with('permissions')->get()->all();
79
80         // Chunk through all books
81         $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
82             $this->buildJointPermissionsForBooks($books, $roles);
83         });
84
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);
89             });
90     }
91
92     /**
93      * Get a query for fetching a book with it's children.
94      */
95     protected function bookFetchQuery(): Builder
96     {
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']);
101                 },
102                 'pages' => function ($query) {
103                     $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']);
104                 },
105             ]);
106     }
107
108     /**
109      * Build joint permissions for the given shelf and role combinations.
110      *
111      * @throws Throwable
112      */
113     protected function buildJointPermissionsForShelves(EloquentCollection $shelves, array $roles, bool $deleteOld = false)
114     {
115         if ($deleteOld) {
116             $this->deleteManyJointPermissionsForEntities($shelves->all());
117         }
118         $this->createManyJointPermissions($shelves->all(), $roles);
119     }
120
121     /**
122      * Build joint permissions for the given book and role combinations.
123      *
124      * @throws Throwable
125      */
126     protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
127     {
128         $entities = clone $books;
129
130         /** @var Book $book */
131         foreach ($books->all() as $book) {
132             foreach ($book->getRelation('chapters') as $chapter) {
133                 $entities->push($chapter);
134             }
135             foreach ($book->getRelation('pages') as $page) {
136                 $entities->push($page);
137             }
138         }
139
140         if ($deleteOld) {
141             $this->deleteManyJointPermissionsForEntities($entities->all());
142         }
143
144         $this->createManyJointPermissions($entities->all(), $roles);
145     }
146
147     /**
148      * Rebuild the entity jointPermissions for a particular entity.
149      *
150      * @throws Throwable
151      */
152     public function buildJointPermissionsForEntity(Entity $entity)
153     {
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);
158
159             return;
160         }
161
162         /** @var BookChild $entity */
163         if ($entity->book) {
164             $entities[] = $entity->book;
165         }
166
167         if ($entity instanceof Page && $entity->chapter_id) {
168             $entities[] = $entity->chapter;
169         }
170
171         if ($entity instanceof Chapter) {
172             foreach ($entity->pages as $page) {
173                 $entities[] = $page;
174             }
175         }
176
177         $this->buildJointPermissionsForEntities($entities);
178     }
179
180     /**
181      * Rebuild the entity jointPermissions for a collection of entities.
182      *
183      * @throws Throwable
184      */
185     protected function buildJointPermissionsForEntities(array $entities)
186     {
187         $roles = Role::query()->get()->values()->all();
188         $this->deleteManyJointPermissionsForEntities($entities);
189         $this->createManyJointPermissions($entities, $roles);
190     }
191
192     /**
193      * Build the entity jointPermissions for a particular role.
194      */
195     public function buildJointPermissionForRole(Role $role)
196     {
197         $roles = [$role];
198         $role->jointPermissions()->delete();
199
200         // Chunk through all books
201         $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
202             $this->buildJointPermissionsForBooks($books, $roles);
203         });
204
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);
209             });
210     }
211
212     /**
213      * Delete all the entity jointPermissions for a list of entities.
214      *
215      * @param Entity[] $entities
216      *
217      * @throws Throwable
218      */
219     protected function deleteManyJointPermissionsForEntities(array $entities)
220     {
221         $idsByType = $this->entitiesToTypeIdMap($entities);
222
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)
229                         ->delete();
230                 }
231             }
232         });
233     }
234
235     /**
236      * Create & Save entity jointPermissions for many entities and roles.
237      *
238      * @param Entity[] $entities
239      * @param Role[]   $roles
240      *
241      * @throws Throwable
242      */
243     protected function createManyJointPermissions(array $entities, array $roles)
244     {
245         $this->readyEntityCache($entities);
246         $jointPermissions = [];
247
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'));
252         }
253
254         // Fetch related entity permissions
255         $permissions = $this->getEntityPermissionsForEntities($entities);
256
257         // Create a mapping of explicit entity permissions
258         $permissionMap = [];
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;
263         }
264
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;
270             }
271         }
272
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);
278                 }
279             }
280         }
281
282         DB::transaction(function () use ($jointPermissions) {
283             foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
284                 DB::table('joint_permissions')->insert($jointPermissionChunk);
285             }
286         });
287     }
288
289     /**
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[]>
294      */
295     protected function entitiesToTypeIdMap(array $entities): array
296     {
297         $idsByType = [];
298
299         foreach ($entities as $entity) {
300             $type = $entity->getMorphClass();
301
302             if (!isset($idsByType[$type])) {
303                 $idsByType[$type] = [];
304             }
305
306             $idsByType[$type][] = $entity->getRawAttribute('id');
307         }
308
309         return $idsByType;
310     }
311
312     /**
313      * Get the entity permissions for all the given entities
314      * @param Entity[] $entities
315      * @return EloquentCollection
316      */
317     protected function getEntityPermissionsForEntities(array $entities)
318     {
319         $idsByType = $this->entitiesToTypeIdMap($entities);
320         $permissionFetch = EntityPermission::query();
321
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);
325             });
326         }
327
328         return $permissionFetch->get();
329     }
330
331     /**
332      * Get the actions related to an entity.
333      */
334     protected function getActions(Entity $entity): array
335     {
336         $baseActions = ['view', 'update', 'delete'];
337         if ($entity instanceof Chapter || $entity instanceof Book) {
338             $baseActions[] = 'page-create';
339         }
340         if ($entity instanceof Book) {
341             $baseActions[] = 'chapter-create';
342         }
343
344         return $baseActions;
345     }
346
347     /**
348      * Create entity permission data for an entity and role
349      * for a particular action.
350      */
351     protected function createJointPermissionData(Entity $entity, Role $role, string $action, array $permissionMap, array $rolePermissionMap): array
352     {
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);
358
359         if ($role->system_name === 'admin') {
360             return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
361         }
362
363         if ($entity->restricted) {
364             $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
365
366             return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
367         }
368
369         if ($entity instanceof Book || $entity instanceof Bookshelf) {
370             return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
371         }
372
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;
377
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);
384             }
385         }
386
387         return $this->createJointPermissionDataArray(
388             $entity,
389             $role,
390             $action,
391             ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
392             ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
393         );
394     }
395
396     /**
397      * Check for an active restriction in an entity map.
398      */
399     protected function mapHasActiveRestriction(array $entityMap, Entity $entity, Role $role, string $action): bool
400     {
401         $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
402
403         return $entityMap[$key] ?? false;
404     }
405
406     /**
407      * Create an array of data with the information of an entity jointPermissions.
408      * Used to build data for bulk insertion.
409      */
410     protected function createJointPermissionDataArray(Entity $entity, Role $role, string $action, bool $permissionAll, bool $permissionOwn): array
411     {
412         return [
413             'action'             => $action,
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'),
420         ];
421     }
422
423 }