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.
54 * @param JointPermission $jointPermission
55 * @param EntityPermission $entityPermission
57 * @param Connection $db
58 * @param EntityProvider $entityProvider
60 public function __construct(
61 JointPermission $jointPermission,
62 Permissions\EntityPermission $entityPermission,
65 EntityProvider $entityProvider
68 $this->jointPermission = $jointPermission;
69 $this->entityPermission = $entityPermission;
71 $this->entityProvider = $entityProvider;
75 * Set the database connection
76 * @param Connection $connection
78 public function setConnection(Connection $connection)
80 $this->db = $connection;
84 * Prepare the local entity cache and ensure it's empty
85 * @param \BookStack\Entities\Entity[] $entities
87 protected function readyEntityCache($entities = [])
89 $this->entityCache = [];
91 foreach ($entities as $entity) {
92 $type = $entity->getType();
93 if (!isset($this->entityCache[$type])) {
94 $this->entityCache[$type] = collect();
96 $this->entityCache[$type]->put($entity->id, $entity);
101 * Get a book via ID, Checks local cache
105 protected function getBook($bookId)
107 if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
108 return $this->entityCache['book']->get($bookId);
111 $book = $this->entityProvider->book->find($bookId);
112 if ($book === null) {
120 * Get a chapter via ID, Checks local cache
122 * @return \BookStack\Entities\Book
124 protected function getChapter($chapterId)
126 if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
127 return $this->entityCache['chapter']->get($chapterId);
130 $chapter = $this->entityProvider->chapter->find($chapterId);
131 if ($chapter === null) {
139 * Get the roles for the current user;
142 protected function getRoles()
144 if ($this->userRoles !== false) {
145 return $this->userRoles;
150 if (auth()->guest()) {
151 $roles[] = $this->role->getSystemRole('public')->id;
156 foreach ($this->currentUser()->roles as $role) {
157 $roles[] = $role->id;
163 * Re-generate all entity permission from scratch.
165 public function buildJointPermissions()
167 $this->jointPermission->truncate();
168 $this->readyEntityCache();
170 // Get all roles (Should be the most limited dimension)
171 $roles = $this->role->with('permissions')->get()->all();
173 // Chunk through all books
174 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
175 $this->buildJointPermissionsForBooks($books, $roles);
178 // Chunk through all bookshelves
179 $this->entityProvider->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
180 ->chunk(50, function ($shelves) use ($roles) {
181 $this->buildJointPermissionsForShelves($shelves, $roles);
186 * Get a query for fetching a book with it's children.
187 * @return QueryBuilder
189 protected function bookFetchQuery()
191 return $this->entityProvider->book->newQuery()
192 ->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
193 $query->select(['id', 'restricted', 'created_by', 'book_id']);
194 }, 'pages' => function ($query) {
195 $query->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
200 * @param Collection $shelves
201 * @param array $roles
202 * @param bool $deleteOld
205 protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false)
208 $this->deleteManyJointPermissionsForEntities($shelves->all());
210 $this->createManyJointPermissions($shelves, $roles);
214 * Build joint permissions for an array of books
215 * @param Collection $books
216 * @param array $roles
217 * @param bool $deleteOld
219 protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
221 $entities = clone $books;
223 /** @var Book $book */
224 foreach ($books->all() as $book) {
225 foreach ($book->getRelation('chapters') as $chapter) {
226 $entities->push($chapter);
228 foreach ($book->getRelation('pages') as $page) {
229 $entities->push($page);
234 $this->deleteManyJointPermissionsForEntities($entities->all());
236 $this->createManyJointPermissions($entities, $roles);
240 * Rebuild the entity jointPermissions for a particular entity.
241 * @param \BookStack\Entities\Entity $entity
244 public function buildJointPermissionsForEntity(Entity $entity)
246 $entities = [$entity];
247 if ($entity->isA('book')) {
248 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
249 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
254 $entities[] = $entity->book;
257 if ($entity->isA('page') && $entity->chapter_id) {
258 $entities[] = $entity->chapter;
261 if ($entity->isA('chapter')) {
262 foreach ($entity->pages as $page) {
267 $this->buildJointPermissionsForEntities(collect($entities));
271 * Rebuild the entity jointPermissions for a collection of entities.
272 * @param Collection $entities
275 public function buildJointPermissionsForEntities(Collection $entities)
277 $roles = $this->role->newQuery()->get();
278 $this->deleteManyJointPermissionsForEntities($entities->all());
279 $this->createManyJointPermissions($entities, $roles);
283 * Build the entity jointPermissions for a particular role.
286 public function buildJointPermissionForRole(Role $role)
289 $this->deleteManyJointPermissionsForRoles($roles);
291 // Chunk through all books
292 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
293 $this->buildJointPermissionsForBooks($books, $roles);
296 // Chunk through all bookshelves
297 $this->entityProvider->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
298 ->chunk(50, function ($shelves) use ($roles) {
299 $this->buildJointPermissionsForShelves($shelves, $roles);
304 * Delete the entity jointPermissions attached to a particular role.
307 public function deleteJointPermissionsForRole(Role $role)
309 $this->deleteManyJointPermissionsForRoles([$role]);
313 * Delete all of the entity jointPermissions for a list of entities.
314 * @param Role[] $roles
316 protected function deleteManyJointPermissionsForRoles($roles)
318 $roleIds = array_map(function ($role) {
321 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
325 * Delete the entity jointPermissions for a particular entity.
326 * @param Entity $entity
329 public function deleteJointPermissionsForEntity(Entity $entity)
331 $this->deleteManyJointPermissionsForEntities([$entity]);
335 * Delete all of the entity jointPermissions for a list of entities.
336 * @param \BookStack\Entities\Entity[] $entities
339 protected function deleteManyJointPermissionsForEntities($entities)
341 if (count($entities) === 0) {
345 $this->db->transaction(function () use ($entities) {
347 foreach (array_chunk($entities, 1000) as $entityChunk) {
348 $query = $this->db->table('joint_permissions');
349 foreach ($entityChunk as $entity) {
350 $query->orWhere(function (QueryBuilder $query) use ($entity) {
351 $query->where('entity_id', '=', $entity->id)
352 ->where('entity_type', '=', $entity->getMorphClass());
361 * Create & Save entity jointPermissions for many entities and jointPermissions.
362 * @param Collection $entities
363 * @param array $roles
366 protected function createManyJointPermissions($entities, $roles)
368 $this->readyEntityCache($entities);
369 $jointPermissions = [];
371 // Fetch Entity Permissions and create a mapping of entity restricted statuses
372 $entityRestrictedMap = [];
373 $permissionFetch = $this->entityPermission->newQuery();
374 foreach ($entities as $entity) {
375 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
376 $permissionFetch->orWhere(function ($query) use ($entity) {
377 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
380 $permissions = $permissionFetch->get();
382 // Create a mapping of explicit entity permissions
384 foreach ($permissions as $permission) {
385 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
386 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
387 $permissionMap[$key] = $isRestricted;
390 // Create a mapping of role permissions
391 $rolePermissionMap = [];
392 foreach ($roles as $role) {
393 foreach ($role->permissions as $permission) {
394 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
398 // Create Joint Permission Data
399 foreach ($entities as $entity) {
400 foreach ($roles as $role) {
401 foreach ($this->getActions($entity) as $action) {
402 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
407 $this->db->transaction(function () use ($jointPermissions) {
408 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
409 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
416 * Get the actions related to an entity.
417 * @param \BookStack\Entities\Entity $entity
420 protected function getActions(Entity $entity)
422 $baseActions = ['view', 'update', 'delete'];
423 if ($entity->isA('chapter') || $entity->isA('book')) {
424 $baseActions[] = 'page-create';
426 if ($entity->isA('book')) {
427 $baseActions[] = 'chapter-create';
433 * Create entity permission data for an entity and role
434 * for a particular action.
435 * @param Entity $entity
437 * @param string $action
438 * @param array $permissionMap
439 * @param array $rolePermissionMap
442 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
444 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
445 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
446 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
447 $explodedAction = explode('-', $action);
448 $restrictionAction = end($explodedAction);
450 if ($role->system_name === 'admin') {
451 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
454 if ($entity->restricted) {
455 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
456 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
459 if ($entity->isA('book') || $entity->isA('bookshelf')) {
460 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
463 // For chapters and pages, Check if explicit permissions are set on the Book.
464 $book = $this->getBook($entity->book_id);
465 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
466 $hasPermissiveAccessToParents = !$book->restricted;
468 // For pages with a chapter, Check if explicit permissions are set on the Chapter
469 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
470 $chapter = $this->getChapter($entity->chapter_id);
471 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
472 if ($chapter->restricted) {
473 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
477 return $this->createJointPermissionDataArray(
481 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
482 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
487 * Check for an active restriction in an entity map.
489 * @param Entity $entity
494 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
496 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
497 return isset($entityMap[$key]) ? $entityMap[$key] : false;
501 * Create an array of data with the information of an entity jointPermissions.
502 * Used to build data for bulk insertion.
503 * @param \BookStack\Entities\Entity $entity
506 * @param $permissionAll
507 * @param $permissionOwn
510 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
513 'role_id' => $role->getRawAttribute('id'),
514 'entity_id' => $entity->getRawAttribute('id'),
515 'entity_type' => $entity->getMorphClass(),
517 'has_permission' => $permissionAll,
518 'has_permission_own' => $permissionOwn,
519 'created_by' => $entity->getRawAttribute('created_by')
524 * Checks if an entity has a restriction set upon it.
525 * @param Ownable $ownable
529 public function checkOwnableUserAccess(Ownable $ownable, $permission)
531 $explodedPermission = explode('-', $permission);
533 $baseQuery = $ownable->where('id', '=', $ownable->id);
534 $action = end($explodedPermission);
535 $this->currentAction = $action;
537 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
539 // Handle non entity specific jointPermissions
540 if (in_array($explodedPermission[0], $nonJointPermissions)) {
541 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
542 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
543 $this->currentAction = 'view';
544 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
545 return ($allPermission || ($isOwner && $ownPermission));
548 // Handle abnormal create jointPermissions
549 if ($action === 'create') {
550 $this->currentAction = $permission;
553 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
559 * Checks if a user has the given permission for any items in the system.
560 * Can be passed an entity instance to filter on a specific type.
561 * @param string $permission
562 * @param string $entityClass
565 public function checkUserHasPermissionOnAnything(string $permission, string $entityClass = null)
567 $userRoleIds = $this->currentUser()->roles()->select('id')->pluck('id')->toArray();
568 $userId = $this->currentUser()->id;
570 $permissionQuery = $this->db->table('joint_permissions')
571 ->where('action', '=', $permission)
572 ->whereIn('role_id', $userRoleIds)
573 ->where(function ($query) use ($userId) {
574 $query->where('has_permission', '=', 1)
575 ->orWhere(function ($query2) use ($userId) {
576 $query2->where('has_permission_own', '=', 1)
577 ->where('created_by', '=', $userId);
581 if (!is_null($entityClass)) {
582 $entityInstance = app()->make($entityClass);
583 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
586 $hasPermission = $permissionQuery->count() > 0;
588 return $hasPermission;
592 * Check if an entity has restrictions set on itself or its
594 * @param \BookStack\Entities\Entity $entity
598 public function checkIfRestrictionsSet(Entity $entity, $action)
600 $this->currentAction = $action;
601 if ($entity->isA('page')) {
602 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
603 } elseif ($entity->isA('chapter')) {
604 return $entity->restricted || $entity->book->restricted;
605 } elseif ($entity->isA('book')) {
606 return $entity->restricted;
611 * The general query filter to remove all entities
612 * that the current user does not have access to.
616 protected function entityRestrictionQuery($query)
618 $q = $query->where(function ($parentQuery) {
619 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
620 $permissionQuery->whereIn('role_id', $this->getRoles())
621 ->where('action', '=', $this->currentAction)
622 ->where(function ($query) {
623 $query->where('has_permission', '=', true)
624 ->orWhere(function ($query) {
625 $query->where('has_permission_own', '=', true)
626 ->where('created_by', '=', $this->currentUser()->id);
636 * Get the children of a book in an efficient single query, Filtered by the permission system.
637 * @param integer $book_id
638 * @param bool $filterDrafts
639 * @param bool $fetchPageContent
640 * @return QueryBuilder
642 public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false)
644 $entities = $this->entityProvider;
645 $pageSelect = $this->db->table('pages')->selectRaw($entities->page->entityRawQuery($fetchPageContent))
646 ->where('book_id', '=', $book_id)->where(function ($query) use ($filterDrafts) {
647 $query->where('draft', '=', 0);
648 if (!$filterDrafts) {
649 $query->orWhere(function ($query) {
650 $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
654 $chapterSelect = $this->db->table('chapters')->selectRaw($entities->chapter->entityRawQuery())->where('book_id', '=', $book_id);
655 $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
656 ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
658 // Add joint permission filter
659 $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
660 ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
661 ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
662 ->where(function ($query) {
663 $query->where('jp.has_permission', '=', 1)->orWhere(function ($query) {
664 $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
667 $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
669 $query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
675 * Add restrictions for a generic entity
676 * @param string $entityType
677 * @param Builder|\BookStack\Entities\Entity $query
678 * @param string $action
681 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
683 if (strtolower($entityType) === 'page') {
684 // Prevent drafts being visible to others.
685 $query = $query->where(function ($query) {
686 $query->where('draft', '=', false)
687 ->orWhere(function ($query) {
688 $query->where('draft', '=', true)
689 ->where('created_by', '=', $this->currentUser()->id);
694 $this->currentAction = $action;
695 return $this->entityRestrictionQuery($query);
699 * Filter items that have entities set as a polymorphic relation.
701 * @param string $tableName
702 * @param string $entityIdColumn
703 * @param string $entityTypeColumn
704 * @param string $action
705 * @return QueryBuilder
707 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
710 $this->currentAction = $action;
711 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
713 $q = $query->where(function ($query) use ($tableDetails) {
714 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
715 $permissionQuery->select('id')->from('joint_permissions')
716 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
717 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
718 ->where('action', '=', $this->currentAction)
719 ->whereIn('role_id', $this->getRoles())
720 ->where(function ($query) {
721 $query->where('has_permission', '=', true)->orWhere(function ($query) {
722 $query->where('has_permission_own', '=', true)
723 ->where('created_by', '=', $this->currentUser()->id);
733 * Add conditions to a query to filter the selection to related entities
734 * where permissions are granted.
738 * @param $entityIdColumn
741 public function filterRelatedEntity($entityType, $query, $tableName, $entityIdColumn)
743 $this->currentAction = 'view';
744 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
746 $pageMorphClass = $this->entityProvider->get($entityType)->getMorphClass();
748 $q = $query->where(function ($query) use ($tableDetails, $pageMorphClass) {
749 $query->where(function ($query) use (&$tableDetails, $pageMorphClass) {
750 $query->whereExists(function ($permissionQuery) use (&$tableDetails, $pageMorphClass) {
751 $permissionQuery->select('id')->from('joint_permissions')
752 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
753 ->where('entity_type', '=', $pageMorphClass)
754 ->where('action', '=', $this->currentAction)
755 ->whereIn('role_id', $this->getRoles())
756 ->where(function ($query) {
757 $query->where('has_permission', '=', true)->orWhere(function ($query) {
758 $query->where('has_permission_own', '=', true)
759 ->where('created_by', '=', $this->currentUser()->id);
763 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
772 * Get the current user
773 * @return \BookStack\Auth\User
775 private function currentUser()
777 if ($this->currentUserModel === false) {
778 $this->currentUserModel = user();
781 return $this->currentUserModel;
785 * Clean the cached user elements.
787 private function clean()
789 $this->currentUserModel = false;
790 $this->userRoles = false;
791 $this->isAdminUser = null;