1 <?php namespace BookStack\Auth\Permissions;
3 use BookStack\Auth\Permissions;
4 use BookStack\Auth\Role;
5 use BookStack\Entities\Book;
6 use BookStack\Entities\Bookshelf;
7 use BookStack\Entities\Chapter;
8 use BookStack\Entities\Entity;
9 use BookStack\Entities\EntityProvider;
10 use BookStack\Entities\Page;
11 use BookStack\Ownable;
12 use Illuminate\Database\Connection;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Query\Builder as QueryBuilder;
15 use Illuminate\Support\Collection;
17 class PermissionService
20 protected $currentAction;
21 protected $isAdminUser;
22 protected $userRoles = false;
23 protected $currentUserModel = false;
31 * @var JointPermission
33 protected $jointPermission;
41 * @var EntityPermission
43 protected $entityPermission;
48 protected $entityProvider;
50 protected $entityCache;
53 * PermissionService constructor.
55 public function __construct(
56 JointPermission $jointPermission,
57 Permissions\EntityPermission $entityPermission,
60 EntityProvider $entityProvider
63 $this->jointPermission = $jointPermission;
64 $this->entityPermission = $entityPermission;
66 $this->entityProvider = $entityProvider;
70 * Set the database connection
71 * @param Connection $connection
73 public function setConnection(Connection $connection)
75 $this->db = $connection;
79 * Prepare the local entity cache and ensure it's empty
80 * @param \BookStack\Entities\Entity[] $entities
82 protected function readyEntityCache($entities = [])
84 $this->entityCache = [];
86 foreach ($entities as $entity) {
87 $type = $entity->getType();
88 if (!isset($this->entityCache[$type])) {
89 $this->entityCache[$type] = collect();
91 $this->entityCache[$type]->put($entity->id, $entity);
96 * Get a book via ID, Checks local cache
100 protected function getBook($bookId)
102 if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
103 return $this->entityCache['book']->get($bookId);
106 $book = $this->entityProvider->book->find($bookId);
107 if ($book === null) {
115 * Get a chapter via ID, Checks local cache
117 * @return \BookStack\Entities\Book
119 protected function getChapter($chapterId)
121 if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
122 return $this->entityCache['chapter']->get($chapterId);
125 $chapter = $this->entityProvider->chapter->find($chapterId);
126 if ($chapter === null) {
134 * Get the roles for the current user;
137 protected function getRoles()
139 if ($this->userRoles !== false) {
140 return $this->userRoles;
145 if (auth()->guest()) {
146 $roles[] = $this->role->getSystemRole('public')->id;
151 foreach ($this->currentUser()->roles as $role) {
152 $roles[] = $role->id;
158 * Re-generate all entity permission from scratch.
160 public function buildJointPermissions()
162 $this->jointPermission->truncate();
163 $this->readyEntityCache();
165 // Get all roles (Should be the most limited dimension)
166 $roles = $this->role->with('permissions')->get()->all();
168 // Chunk through all books
169 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
170 $this->buildJointPermissionsForBooks($books, $roles);
173 // Chunk through all bookshelves
174 $this->entityProvider->bookshelf->newQuery()->withTrashed()->select(['id', 'restricted', 'created_by'])
175 ->chunk(50, function ($shelves) use ($roles) {
176 $this->buildJointPermissionsForShelves($shelves, $roles);
181 * Get a query for fetching a book with it's children.
182 * @return QueryBuilder
184 protected function bookFetchQuery()
186 return $this->entityProvider->book->withTrashed()->newQuery()
187 ->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
188 $query->withTrashed()->select(['id', 'restricted', 'created_by', 'book_id']);
189 }, 'pages' => function ($query) {
190 $query->withTrashed()->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
195 * @param Collection $shelves
196 * @param array $roles
197 * @param bool $deleteOld
200 protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false)
203 $this->deleteManyJointPermissionsForEntities($shelves->all());
205 $this->createManyJointPermissions($shelves, $roles);
209 * Build joint permissions for an array of books
210 * @param Collection $books
211 * @param array $roles
212 * @param bool $deleteOld
214 protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
216 $entities = clone $books;
218 /** @var Book $book */
219 foreach ($books->all() as $book) {
220 foreach ($book->getRelation('chapters') as $chapter) {
221 $entities->push($chapter);
223 foreach ($book->getRelation('pages') as $page) {
224 $entities->push($page);
229 $this->deleteManyJointPermissionsForEntities($entities->all());
231 $this->createManyJointPermissions($entities, $roles);
235 * Rebuild the entity jointPermissions for a particular entity.
236 * @param \BookStack\Entities\Entity $entity
239 public function buildJointPermissionsForEntity(Entity $entity)
241 $entities = [$entity];
242 if ($entity->isA('book')) {
243 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
244 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
249 $entities[] = $entity->book;
252 if ($entity->isA('page') && $entity->chapter_id) {
253 $entities[] = $entity->chapter;
256 if ($entity->isA('chapter')) {
257 foreach ($entity->pages as $page) {
262 $this->buildJointPermissionsForEntities(collect($entities));
266 * Rebuild the entity jointPermissions for a collection of entities.
267 * @param Collection $entities
270 public function buildJointPermissionsForEntities(Collection $entities)
272 $roles = $this->role->newQuery()->get();
273 $this->deleteManyJointPermissionsForEntities($entities->all());
274 $this->createManyJointPermissions($entities, $roles);
278 * Build the entity jointPermissions for a particular role.
281 public function buildJointPermissionForRole(Role $role)
284 $this->deleteManyJointPermissionsForRoles($roles);
286 // Chunk through all books
287 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
288 $this->buildJointPermissionsForBooks($books, $roles);
291 // Chunk through all bookshelves
292 $this->entityProvider->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
293 ->chunk(50, function ($shelves) use ($roles) {
294 $this->buildJointPermissionsForShelves($shelves, $roles);
299 * Delete the entity jointPermissions attached to a particular role.
302 public function deleteJointPermissionsForRole(Role $role)
304 $this->deleteManyJointPermissionsForRoles([$role]);
308 * Delete all of the entity jointPermissions for a list of entities.
309 * @param Role[] $roles
311 protected function deleteManyJointPermissionsForRoles($roles)
313 $roleIds = array_map(function ($role) {
316 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
320 * Delete the entity jointPermissions for a particular entity.
321 * @param Entity $entity
324 public function deleteJointPermissionsForEntity(Entity $entity)
326 $this->deleteManyJointPermissionsForEntities([$entity]);
330 * Delete all of the entity jointPermissions for a list of entities.
331 * @param \BookStack\Entities\Entity[] $entities
334 protected function deleteManyJointPermissionsForEntities($entities)
336 if (count($entities) === 0) {
340 $this->db->transaction(function () use ($entities) {
342 foreach (array_chunk($entities, 1000) as $entityChunk) {
343 $query = $this->db->table('joint_permissions');
344 foreach ($entityChunk as $entity) {
345 $query->orWhere(function (QueryBuilder $query) use ($entity) {
346 $query->where('entity_id', '=', $entity->id)
347 ->where('entity_type', '=', $entity->getMorphClass());
356 * Create & Save entity jointPermissions for many entities and jointPermissions.
357 * @param Collection $entities
358 * @param array $roles
361 protected function createManyJointPermissions($entities, $roles)
363 $this->readyEntityCache($entities);
364 $jointPermissions = [];
366 // Fetch Entity Permissions and create a mapping of entity restricted statuses
367 $entityRestrictedMap = [];
368 $permissionFetch = $this->entityPermission->newQuery();
369 foreach ($entities as $entity) {
370 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
371 $permissionFetch->orWhere(function ($query) use ($entity) {
372 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
375 $permissions = $permissionFetch->get();
377 // Create a mapping of explicit entity permissions
379 foreach ($permissions as $permission) {
380 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
381 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
382 $permissionMap[$key] = $isRestricted;
385 // Create a mapping of role permissions
386 $rolePermissionMap = [];
387 foreach ($roles as $role) {
388 foreach ($role->permissions as $permission) {
389 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
393 // Create Joint Permission Data
394 foreach ($entities as $entity) {
395 foreach ($roles as $role) {
396 foreach ($this->getActions($entity) as $action) {
397 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
402 $this->db->transaction(function () use ($jointPermissions) {
403 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
404 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
411 * Get the actions related to an entity.
412 * @param \BookStack\Entities\Entity $entity
415 protected function getActions(Entity $entity)
417 $baseActions = ['view', 'update', 'delete'];
418 if ($entity->isA('chapter') || $entity->isA('book')) {
419 $baseActions[] = 'page-create';
421 if ($entity->isA('book')) {
422 $baseActions[] = 'chapter-create';
428 * Create entity permission data for an entity and role
429 * for a particular action.
430 * @param Entity $entity
432 * @param string $action
433 * @param array $permissionMap
434 * @param array $rolePermissionMap
437 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
439 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
440 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
441 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
442 $explodedAction = explode('-', $action);
443 $restrictionAction = end($explodedAction);
445 if ($role->system_name === 'admin') {
446 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
449 if ($entity->restricted) {
450 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
451 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
454 if ($entity->isA('book') || $entity->isA('bookshelf')) {
455 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
458 // For chapters and pages, Check if explicit permissions are set on the Book.
459 $book = $this->getBook($entity->book_id);
460 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
461 $hasPermissiveAccessToParents = !$book->restricted;
463 // For pages with a chapter, Check if explicit permissions are set on the Chapter
464 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
465 $chapter = $this->getChapter($entity->chapter_id);
466 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
467 if ($chapter->restricted) {
468 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
472 return $this->createJointPermissionDataArray(
476 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
477 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
482 * Check for an active restriction in an entity map.
484 * @param Entity $entity
489 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
491 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
492 return isset($entityMap[$key]) ? $entityMap[$key] : false;
496 * Create an array of data with the information of an entity jointPermissions.
497 * Used to build data for bulk insertion.
498 * @param \BookStack\Entities\Entity $entity
501 * @param $permissionAll
502 * @param $permissionOwn
505 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
508 'role_id' => $role->getRawAttribute('id'),
509 'entity_id' => $entity->getRawAttribute('id'),
510 'entity_type' => $entity->getMorphClass(),
512 'has_permission' => $permissionAll,
513 'has_permission_own' => $permissionOwn,
514 'created_by' => $entity->getRawAttribute('created_by')
519 * Checks if an entity has a restriction set upon it.
520 * @param Ownable $ownable
524 public function checkOwnableUserAccess(Ownable $ownable, $permission)
526 $explodedPermission = explode('-', $permission);
528 $baseQuery = $ownable->where('id', '=', $ownable->id);
529 $action = end($explodedPermission);
530 $this->currentAction = $action;
532 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
534 // Handle non entity specific jointPermissions
535 if (in_array($explodedPermission[0], $nonJointPermissions)) {
536 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
537 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
538 $this->currentAction = 'view';
539 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
540 return ($allPermission || ($isOwner && $ownPermission));
543 // Handle abnormal create jointPermissions
544 if ($action === 'create') {
545 $this->currentAction = $permission;
548 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
554 * Checks if a user has the given permission for any items in the system.
555 * Can be passed an entity instance to filter on a specific type.
556 * @param string $permission
557 * @param string $entityClass
560 public function checkUserHasPermissionOnAnything(string $permission, string $entityClass = null)
562 $userRoleIds = $this->currentUser()->roles()->select('id')->pluck('id')->toArray();
563 $userId = $this->currentUser()->id;
565 $permissionQuery = $this->db->table('joint_permissions')
566 ->where('action', '=', $permission)
567 ->whereIn('role_id', $userRoleIds)
568 ->where(function ($query) use ($userId) {
569 $query->where('has_permission', '=', 1)
570 ->orWhere(function ($query2) use ($userId) {
571 $query2->where('has_permission_own', '=', 1)
572 ->where('created_by', '=', $userId);
576 if (!is_null($entityClass)) {
577 $entityInstance = app()->make($entityClass);
578 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
581 $hasPermission = $permissionQuery->count() > 0;
583 return $hasPermission;
587 * Check if an entity has restrictions set on itself or its
589 * @param \BookStack\Entities\Entity $entity
593 public function checkIfRestrictionsSet(Entity $entity, $action)
595 $this->currentAction = $action;
596 if ($entity->isA('page')) {
597 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
598 } elseif ($entity->isA('chapter')) {
599 return $entity->restricted || $entity->book->restricted;
600 } elseif ($entity->isA('book')) {
601 return $entity->restricted;
606 * The general query filter to remove all entities
607 * that the current user does not have access to.
611 protected function entityRestrictionQuery($query)
613 $q = $query->where(function ($parentQuery) {
614 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
615 $permissionQuery->whereIn('role_id', $this->getRoles())
616 ->where('action', '=', $this->currentAction)
617 ->where(function ($query) {
618 $query->where('has_permission', '=', true)
619 ->orWhere(function ($query) {
620 $query->where('has_permission_own', '=', true)
621 ->where('created_by', '=', $this->currentUser()->id);
631 * Limited the given entity query so that the query will only
632 * return items that the user has permission for the given ability.
634 public function restrictEntityQuery(Builder $query, string $ability = 'view'): Builder
637 return $query->where(function (Builder $parentQuery) use ($ability) {
638 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) use ($ability) {
639 $permissionQuery->whereIn('role_id', $this->getRoles())
640 ->where('action', '=', $ability)
641 ->where(function (Builder $query) {
642 $query->where('has_permission', '=', true)
643 ->orWhere(function (Builder $query) {
644 $query->where('has_permission_own', '=', true)
645 ->where('created_by', '=', $this->currentUser()->id);
653 * Extend the given page query to ensure draft items are not visible
654 * unless created by the given user.
656 public function enforceDraftVisiblityOnQuery(Builder $query): Builder
658 return $query->where(function (Builder $query) {
659 $query->where('draft', '=', false)
660 ->orWhere(function (Builder $query) {
661 $query->where('draft', '=', true)
662 ->where('created_by', '=', $this->currentUser()->id);
668 * Add restrictions for a generic entity
669 * @param string $entityType
670 * @param Builder|\BookStack\Entities\Entity $query
671 * @param string $action
674 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
676 if (strtolower($entityType) === 'page') {
677 // Prevent drafts being visible to others.
678 $query = $query->where(function ($query) {
679 $query->where('draft', '=', false)
680 ->orWhere(function ($query) {
681 $query->where('draft', '=', true)
682 ->where('created_by', '=', $this->currentUser()->id);
687 $this->currentAction = $action;
688 return $this->entityRestrictionQuery($query);
692 * Filter items that have entities set as a polymorphic relation.
694 * @param string $tableName
695 * @param string $entityIdColumn
696 * @param string $entityTypeColumn
697 * @param string $action
698 * @return QueryBuilder
700 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
703 $this->currentAction = $action;
704 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
706 $q = $query->where(function ($query) use ($tableDetails) {
707 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
708 $permissionQuery->select('id')->from('joint_permissions')
709 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
710 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
711 ->where('action', '=', $this->currentAction)
712 ->whereIn('role_id', $this->getRoles())
713 ->where(function ($query) {
714 $query->where('has_permission', '=', true)->orWhere(function ($query) {
715 $query->where('has_permission_own', '=', true)
716 ->where('created_by', '=', $this->currentUser()->id);
726 * Add conditions to a query to filter the selection to related entities
727 * where permissions are granted.
731 * @param $entityIdColumn
734 public function filterRelatedEntity($entityType, $query, $tableName, $entityIdColumn)
736 $this->currentAction = 'view';
737 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
739 $pageMorphClass = $this->entityProvider->get($entityType)->getMorphClass();
741 $q = $query->where(function ($query) use ($tableDetails, $pageMorphClass) {
742 $query->where(function ($query) use (&$tableDetails, $pageMorphClass) {
743 $query->whereExists(function ($permissionQuery) use (&$tableDetails, $pageMorphClass) {
744 $permissionQuery->select('id')->from('joint_permissions')
745 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
746 ->where('entity_type', '=', $pageMorphClass)
747 ->where('action', '=', $this->currentAction)
748 ->whereIn('role_id', $this->getRoles())
749 ->where(function ($query) {
750 $query->where('has_permission', '=', true)->orWhere(function ($query) {
751 $query->where('has_permission_own', '=', true)
752 ->where('created_by', '=', $this->currentUser()->id);
756 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
765 * Get the current user
766 * @return \BookStack\Auth\User
768 private function currentUser()
770 if ($this->currentUserModel === false) {
771 $this->currentUserModel = user();
774 return $this->currentUserModel;
778 * Clean the cached user elements.
780 private function clean()
782 $this->currentUserModel = false;
783 $this->userRoles = false;
784 $this->isAdminUser = null;