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 * Re-generate all entity permission from scratch.
26 public function rebuildForAll()
28 JointPermission::query()->truncate();
29 $this->readyEntityCache();
31 // Get all roles (Should be the most limited dimension)
32 $roles = Role::query()->with('permissions')->get()->all();
34 // Chunk through all books
35 $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
36 $this->buildJointPermissionsForBooks($books, $roles);
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);
47 * Rebuild the entity jointPermissions for a particular entity.
51 public function rebuildForEntity(Entity $entity)
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);
61 /** @var BookChild $entity */
63 $entities[] = $entity->book;
66 if ($entity instanceof Page && $entity->chapter_id) {
67 $entities[] = $entity->chapter;
70 if ($entity instanceof Chapter) {
71 foreach ($entity->pages as $page) {
76 $this->buildJointPermissionsForEntities($entities);
80 * Build the entity jointPermissions for a particular role.
82 public function rebuildForRole(Role $role)
85 $role->jointPermissions()->delete();
87 // Chunk through all books
88 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
89 $this->buildJointPermissionsForBooks($books, $roles);
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);
100 * Prepare the local entity cache and ensure it's empty.
102 * @param Entity[] $entities
104 protected function readyEntityCache(array $entities = [])
106 $this->entityCache = [];
108 foreach ($entities as $entity) {
109 $class = get_class($entity);
111 if (!isset($this->entityCache[$class])) {
112 $this->entityCache[$class] = [];
115 $this->entityCache[$class][$entity->getRawAttribute('id')] = $entity;
120 * Get a book via ID, Checks local cache.
122 protected function getBook(int $bookId): ?Book
124 if ($this->entityCache[Book::class][$bookId] ?? false) {
125 return $this->entityCache[Book::class][$bookId];
128 return Book::query()->withTrashed()->find($bookId);
132 * Get a chapter via ID, Checks local cache.
134 protected function getChapter(int $chapterId): ?Chapter
136 if ($this->entityCache[Chapter::class][$chapterId] ?? false) {
137 return $this->entityCache[Chapter::class][$chapterId];
140 return Chapter::query()
146 * Get a query for fetching a book with it's children.
148 protected function bookFetchQuery(): Builder
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']);
155 'pages' => function ($query) {
156 $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']);
163 * Build joint permissions for the given book and role combinations.
167 protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
169 $entities = clone $books;
171 /** @var Book $book */
172 foreach ($books->all() as $book) {
173 foreach ($book->getRelation('chapters') as $chapter) {
174 $entities->push($chapter);
176 foreach ($book->getRelation('pages') as $page) {
177 $entities->push($page);
182 $this->deleteManyJointPermissionsForEntities($entities->all());
185 $this->createManyJointPermissions($entities->all(), $roles);
189 * Rebuild the entity jointPermissions for a collection of entities.
193 protected function buildJointPermissionsForEntities(array $entities)
195 $roles = Role::query()->get()->values()->all();
196 $this->deleteManyJointPermissionsForEntities($entities);
197 $this->createManyJointPermissions($entities, $roles);
201 * Delete all the entity jointPermissions for a list of entities.
203 * @param Entity[] $entities
207 protected function deleteManyJointPermissionsForEntities(array $entities)
209 $idsByType = $this->entitiesToTypeIdMap($entities);
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)
224 * Create & Save entity jointPermissions for many entities and roles.
226 * @param Entity[] $entities
227 * @param Role[] $roles
231 protected function createManyJointPermissions(array $entities, array $roles)
233 $this->readyEntityCache($entities);
234 $jointPermissions = [];
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'));
242 // Fetch related entity permissions
243 $permissions = $this->getEntityPermissionsForEntities($entities);
245 // Create a mapping of explicit entity permissions
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;
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;
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);
270 DB::transaction(function () use ($jointPermissions) {
271 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
272 DB::table('joint_permissions')->insert($jointPermissionChunk);
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[]>
283 protected function entitiesToTypeIdMap(array $entities): array
287 foreach ($entities as $entity) {
288 $type = $entity->getMorphClass();
290 if (!isset($idsByType[$type])) {
291 $idsByType[$type] = [];
294 $idsByType[$type][] = $entity->getRawAttribute('id');
301 * Get the entity permissions for all the given entities
302 * @param Entity[] $entities
303 * @return EloquentCollection
305 protected function getEntityPermissionsForEntities(array $entities)
307 $idsByType = $this->entitiesToTypeIdMap($entities);
308 $permissionFetch = EntityPermission::query();
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);
316 return $permissionFetch->get();
320 * Get the actions related to an entity.
322 protected function getActions(Entity $entity): array
324 $baseActions = ['view', 'update', 'delete'];
325 if ($entity instanceof Chapter || $entity instanceof Book) {
326 $baseActions[] = 'page-create';
328 if ($entity instanceof Book) {
329 $baseActions[] = 'chapter-create';
336 * Create entity permission data for an entity and role
337 * for a particular action.
339 protected function createJointPermissionData(Entity $entity, Role $role, string $action, array $permissionMap, array $rolePermissionMap): array
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);
347 if ($role->system_name === 'admin') {
348 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
351 if ($entity->restricted) {
352 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
354 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
357 if ($entity instanceof Book || $entity instanceof Bookshelf) {
358 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
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;
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);
375 return $this->createJointPermissionDataArray(
379 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
380 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
385 * Check for an active restriction in an entity map.
387 protected function mapHasActiveRestriction(array $entityMap, Entity $entity, Role $role, string $action): bool
389 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
391 return $entityMap[$key] ?? false;
395 * Create an array of data with the information of an entity jointPermissions.
396 * Used to build data for bulk insertion.
398 protected function createJointPermissionDataArray(Entity $entity, Role $role, string $action, bool $permissionAll, bool $permissionOwn): array
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'),