1 <?php namespace BookStack\Auth\Permissions;
3 use BookStack\Auth\Permissions;
4 use BookStack\Auth\Role;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Chapter;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\EntityProvider;
9 use BookStack\Entities\Models\Page;
11 use BookStack\Traits\HasCreatorAndUpdater;
12 use BookStack\Traits\HasOwner;
13 use Illuminate\Database\Connection;
14 use Illuminate\Database\Eloquent\Builder;
15 use Illuminate\Database\Query\Builder as QueryBuilder;
16 use Illuminate\Support\Collection;
18 class PermissionService
21 protected $currentAction;
22 protected $isAdminUser;
23 protected $userRoles = false;
24 protected $currentUserModel = false;
32 * @var JointPermission
34 protected $jointPermission;
42 * @var EntityPermission
44 protected $entityPermission;
49 protected $entityProvider;
51 protected $entityCache;
54 * PermissionService constructor.
56 public function __construct(
57 JointPermission $jointPermission,
58 Permissions\EntityPermission $entityPermission,
61 EntityProvider $entityProvider
64 $this->jointPermission = $jointPermission;
65 $this->entityPermission = $entityPermission;
67 $this->entityProvider = $entityProvider;
71 * Set the database connection
72 * @param Connection $connection
74 public function setConnection(Connection $connection)
76 $this->db = $connection;
80 * Prepare the local entity cache and ensure it's empty
81 * @param \BookStack\Entities\Models\Entity[] $entities
83 protected function readyEntityCache($entities = [])
85 $this->entityCache = [];
87 foreach ($entities as $entity) {
88 $type = $entity->getType();
89 if (!isset($this->entityCache[$type])) {
90 $this->entityCache[$type] = collect();
92 $this->entityCache[$type]->put($entity->id, $entity);
97 * Get a book via ID, Checks local cache
101 protected function getBook($bookId)
103 if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
104 return $this->entityCache['book']->get($bookId);
107 $book = $this->entityProvider->book->find($bookId);
108 if ($book === null) {
116 * Get a chapter via ID, Checks local cache
118 protected function getChapter(int $chapterId): ?Chapter
120 if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
121 return $this->entityCache['chapter']->get($chapterId);
124 return $this->entityProvider->chapter->newQuery()
130 * Get the roles for the current user;
133 protected function getRoles()
135 if ($this->userRoles !== false) {
136 return $this->userRoles;
141 if (auth()->guest()) {
142 $roles[] = $this->role->getSystemRole('public')->id;
147 foreach ($this->currentUser()->roles as $role) {
148 $roles[] = $role->id;
154 * Re-generate all entity permission from scratch.
156 public function buildJointPermissions()
158 $this->jointPermission->truncate();
159 $this->readyEntityCache();
161 // Get all roles (Should be the most limited dimension)
162 $roles = $this->role->with('permissions')->get()->all();
164 // Chunk through all books
165 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
166 $this->buildJointPermissionsForBooks($books, $roles);
169 // Chunk through all bookshelves
170 $this->entityProvider->bookshelf->newQuery()->withTrashed()->select(['id', 'restricted', 'owned_by'])
171 ->chunk(50, function ($shelves) use ($roles) {
172 $this->buildJointPermissionsForShelves($shelves, $roles);
177 * Get a query for fetching a book with it's children.
178 * @return QueryBuilder
180 protected function bookFetchQuery()
182 return $this->entityProvider->book->withTrashed()->newQuery()
183 ->select(['id', 'restricted', 'owned_by'])->with(['chapters' => function ($query) {
184 $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id']);
185 }, 'pages' => function ($query) {
186 $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']);
191 * @param Collection $shelves
192 * @param array $roles
193 * @param bool $deleteOld
196 protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false)
199 $this->deleteManyJointPermissionsForEntities($shelves->all());
201 $this->createManyJointPermissions($shelves, $roles);
205 * Build joint permissions for an array of books
206 * @param Collection $books
207 * @param array $roles
208 * @param bool $deleteOld
210 protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
212 $entities = clone $books;
214 /** @var Book $book */
215 foreach ($books->all() as $book) {
216 foreach ($book->getRelation('chapters') as $chapter) {
217 $entities->push($chapter);
219 foreach ($book->getRelation('pages') as $page) {
220 $entities->push($page);
225 $this->deleteManyJointPermissionsForEntities($entities->all());
227 $this->createManyJointPermissions($entities, $roles);
231 * Rebuild the entity jointPermissions for a particular entity.
232 * @param \BookStack\Entities\Models\Entity $entity
235 public function buildJointPermissionsForEntity(Entity $entity)
237 $entities = [$entity];
238 if ($entity->isA('book')) {
239 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
240 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
245 $entities[] = $entity->book;
248 if ($entity->isA('page') && $entity->chapter_id) {
249 $entities[] = $entity->chapter;
252 if ($entity->isA('chapter')) {
253 foreach ($entity->pages as $page) {
258 $this->buildJointPermissionsForEntities(collect($entities));
262 * Rebuild the entity jointPermissions for a collection of entities.
263 * @param Collection $entities
266 public function buildJointPermissionsForEntities(Collection $entities)
268 $roles = $this->role->newQuery()->get();
269 $this->deleteManyJointPermissionsForEntities($entities->all());
270 $this->createManyJointPermissions($entities, $roles);
274 * Build the entity jointPermissions for a particular role.
277 public function buildJointPermissionForRole(Role $role)
280 $this->deleteManyJointPermissionsForRoles($roles);
282 // Chunk through all books
283 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
284 $this->buildJointPermissionsForBooks($books, $roles);
287 // Chunk through all bookshelves
288 $this->entityProvider->bookshelf->newQuery()->select(['id', 'restricted', 'owned_by'])
289 ->chunk(50, function ($shelves) use ($roles) {
290 $this->buildJointPermissionsForShelves($shelves, $roles);
295 * Delete the entity jointPermissions attached to a particular role.
298 public function deleteJointPermissionsForRole(Role $role)
300 $this->deleteManyJointPermissionsForRoles([$role]);
304 * Delete all of the entity jointPermissions for a list of entities.
305 * @param Role[] $roles
307 protected function deleteManyJointPermissionsForRoles($roles)
309 $roleIds = array_map(function ($role) {
312 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
316 * Delete the entity jointPermissions for a particular entity.
317 * @param Entity $entity
320 public function deleteJointPermissionsForEntity(Entity $entity)
322 $this->deleteManyJointPermissionsForEntities([$entity]);
326 * Delete all of the entity jointPermissions for a list of entities.
327 * @param \BookStack\Entities\Models\Entity[] $entities
330 protected function deleteManyJointPermissionsForEntities($entities)
332 if (count($entities) === 0) {
336 $this->db->transaction(function () use ($entities) {
338 foreach (array_chunk($entities, 1000) as $entityChunk) {
339 $query = $this->db->table('joint_permissions');
340 foreach ($entityChunk as $entity) {
341 $query->orWhere(function (QueryBuilder $query) use ($entity) {
342 $query->where('entity_id', '=', $entity->id)
343 ->where('entity_type', '=', $entity->getMorphClass());
352 * Create & Save entity jointPermissions for many entities and jointPermissions.
353 * @param Collection $entities
354 * @param array $roles
357 protected function createManyJointPermissions($entities, $roles)
359 $this->readyEntityCache($entities);
360 $jointPermissions = [];
362 // Fetch Entity Permissions and create a mapping of entity restricted statuses
363 $entityRestrictedMap = [];
364 $permissionFetch = $this->entityPermission->newQuery();
365 foreach ($entities as $entity) {
366 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
367 $permissionFetch->orWhere(function ($query) use ($entity) {
368 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
371 $permissions = $permissionFetch->get();
373 // Create a mapping of explicit entity permissions
375 foreach ($permissions as $permission) {
376 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
377 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
378 $permissionMap[$key] = $isRestricted;
381 // Create a mapping of role permissions
382 $rolePermissionMap = [];
383 foreach ($roles as $role) {
384 foreach ($role->permissions as $permission) {
385 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
389 // Create Joint Permission Data
390 foreach ($entities as $entity) {
391 foreach ($roles as $role) {
392 foreach ($this->getActions($entity) as $action) {
393 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
398 $this->db->transaction(function () use ($jointPermissions) {
399 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
400 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
407 * Get the actions related to an entity.
408 * @param \BookStack\Entities\Models\Entity $entity
411 protected function getActions(Entity $entity)
413 $baseActions = ['view', 'update', 'delete'];
414 if ($entity->isA('chapter') || $entity->isA('book')) {
415 $baseActions[] = 'page-create';
417 if ($entity->isA('book')) {
418 $baseActions[] = 'chapter-create';
424 * Create entity permission data for an entity and role
425 * for a particular action.
426 * @param Entity $entity
428 * @param string $action
429 * @param array $permissionMap
430 * @param array $rolePermissionMap
433 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
435 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
436 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
437 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
438 $explodedAction = explode('-', $action);
439 $restrictionAction = end($explodedAction);
441 if ($role->system_name === 'admin') {
442 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
445 if ($entity->restricted) {
446 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
447 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
450 if ($entity->isA('book') || $entity->isA('bookshelf')) {
451 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
454 // For chapters and pages, Check if explicit permissions are set on the Book.
455 $book = $this->getBook($entity->book_id);
456 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
457 $hasPermissiveAccessToParents = !$book->restricted;
459 // For pages with a chapter, Check if explicit permissions are set on the Chapter
460 if ($entity instanceof Page && intval($entity->chapter_id) !== 0) {
461 $chapter = $this->getChapter($entity->chapter_id);
462 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
463 if ($chapter->restricted) {
464 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
468 return $this->createJointPermissionDataArray(
472 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
473 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
478 * Check for an active restriction in an entity map.
480 * @param Entity $entity
485 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
487 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
488 return isset($entityMap[$key]) ? $entityMap[$key] : false;
492 * Create an array of data with the information of an entity jointPermissions.
493 * Used to build data for bulk insertion.
494 * @param \BookStack\Entities\Models\Entity $entity
497 * @param $permissionAll
498 * @param $permissionOwn
501 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
504 'role_id' => $role->getRawAttribute('id'),
505 'entity_id' => $entity->getRawAttribute('id'),
506 'entity_type' => $entity->getMorphClass(),
508 'has_permission' => $permissionAll,
509 'has_permission_own' => $permissionOwn,
510 'owned_by' => $entity->getRawAttribute('owned_by')
515 * Checks if an entity has a restriction set upon it.
516 * @param HasCreatorAndUpdater|HasOwner $ownable
518 public function checkOwnableUserAccess(Model $ownable, string $permission): bool
520 $explodedPermission = explode('-', $permission);
522 $baseQuery = $ownable->newQuery()->where('id', '=', $ownable->id);
523 $action = end($explodedPermission);
524 $this->currentAction = $action;
526 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
528 // Handle non entity specific jointPermissions
529 if (in_array($explodedPermission[0], $nonJointPermissions)) {
530 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
531 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
532 $this->currentAction = 'view';
533 $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
534 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->$ownerField;
535 return ($allPermission || ($isOwner && $ownPermission));
538 // Handle abnormal create jointPermissions
539 if ($action === 'create') {
540 $this->currentAction = $permission;
543 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
549 * Checks if a user has the given permission for any items in the system.
550 * Can be passed an entity instance to filter on a specific type.
551 * @param string $permission
552 * @param string $entityClass
555 public function checkUserHasPermissionOnAnything(string $permission, string $entityClass = null)
557 $userRoleIds = $this->currentUser()->roles()->select('id')->pluck('id')->toArray();
558 $userId = $this->currentUser()->id;
560 $permissionQuery = $this->db->table('joint_permissions')
561 ->where('action', '=', $permission)
562 ->whereIn('role_id', $userRoleIds)
563 ->where(function ($query) use ($userId) {
564 $query->where('has_permission', '=', 1)
565 ->orWhere(function ($query2) use ($userId) {
566 $query2->where('has_permission_own', '=', 1)
567 ->where('owned_by', '=', $userId);
571 if (!is_null($entityClass)) {
572 $entityInstance = app()->make($entityClass);
573 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
576 $hasPermission = $permissionQuery->count() > 0;
578 return $hasPermission;
582 * Check if an entity has restrictions set on itself or its
584 * @param \BookStack\Entities\Models\Entity $entity
588 public function checkIfRestrictionsSet(Entity $entity, $action)
590 $this->currentAction = $action;
591 if ($entity->isA('page')) {
592 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
593 } elseif ($entity->isA('chapter')) {
594 return $entity->restricted || $entity->book->restricted;
595 } elseif ($entity->isA('book')) {
596 return $entity->restricted;
601 * The general query filter to remove all entities
602 * that the current user does not have access to.
606 protected function entityRestrictionQuery($query)
608 $q = $query->where(function ($parentQuery) {
609 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
610 $permissionQuery->whereIn('role_id', $this->getRoles())
611 ->where('action', '=', $this->currentAction)
612 ->where(function ($query) {
613 $query->where('has_permission', '=', true)
614 ->orWhere(function ($query) {
615 $query->where('has_permission_own', '=', true)
616 ->where('owned_by', '=', $this->currentUser()->id);
626 * Limited the given entity query so that the query will only
627 * return items that the user has permission for the given ability.
629 public function restrictEntityQuery(Builder $query, string $ability = 'view'): Builder
632 return $query->where(function (Builder $parentQuery) use ($ability) {
633 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) use ($ability) {
634 $permissionQuery->whereIn('role_id', $this->getRoles())
635 ->where('action', '=', $ability)
636 ->where(function (Builder $query) {
637 $query->where('has_permission', '=', true)
638 ->orWhere(function (Builder $query) {
639 $query->where('has_permission_own', '=', true)
640 ->where('owned_by', '=', $this->currentUser()->id);
648 * Extend the given page query to ensure draft items are not visible
649 * unless created by the given user.
651 public function enforceDraftVisiblityOnQuery(Builder $query): Builder
653 return $query->where(function (Builder $query) {
654 $query->where('draft', '=', false)
655 ->orWhere(function (Builder $query) {
656 $query->where('draft', '=', true)
657 ->where('owned_by', '=', $this->currentUser()->id);
663 * Add restrictions for a generic entity
664 * @param string $entityType
665 * @param Builder|\BookStack\Entities\Models\Entity $query
666 * @param string $action
669 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
671 if (strtolower($entityType) === 'page') {
672 // Prevent drafts being visible to others.
673 $query = $query->where(function ($query) {
674 $query->where('draft', '=', false)
675 ->orWhere(function ($query) {
676 $query->where('draft', '=', true)
677 ->where('owned_by', '=', $this->currentUser()->id);
682 $this->currentAction = $action;
683 return $this->entityRestrictionQuery($query);
687 * Filter items that have entities set as a polymorphic relation.
689 * @param string $tableName
690 * @param string $entityIdColumn
691 * @param string $entityTypeColumn
692 * @param string $action
693 * @return QueryBuilder
695 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
698 $this->currentAction = $action;
699 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
701 $q = $query->where(function ($query) use ($tableDetails) {
702 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
703 $permissionQuery->select('id')->from('joint_permissions')
704 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
705 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
706 ->where('action', '=', $this->currentAction)
707 ->whereIn('role_id', $this->getRoles())
708 ->where(function ($query) {
709 $query->where('has_permission', '=', true)->orWhere(function ($query) {
710 $query->where('has_permission_own', '=', true)
711 ->where('owned_by', '=', $this->currentUser()->id);
721 * Add conditions to a query to filter the selection to related entities
722 * where permissions are granted.
726 * @param $entityIdColumn
729 public function filterRelatedEntity($entityType, $query, $tableName, $entityIdColumn)
731 $this->currentAction = 'view';
732 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
734 $pageMorphClass = $this->entityProvider->get($entityType)->getMorphClass();
736 $q = $query->where(function ($query) use ($tableDetails, $pageMorphClass) {
737 $query->where(function ($query) use (&$tableDetails, $pageMorphClass) {
738 $query->whereExists(function ($permissionQuery) use (&$tableDetails, $pageMorphClass) {
739 $permissionQuery->select('id')->from('joint_permissions')
740 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
741 ->where('entity_type', '=', $pageMorphClass)
742 ->where('action', '=', $this->currentAction)
743 ->whereIn('role_id', $this->getRoles())
744 ->where(function ($query) {
745 $query->where('has_permission', '=', true)->orWhere(function ($query) {
746 $query->where('has_permission_own', '=', true)
747 ->where('owned_by', '=', $this->currentUser()->id);
751 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
760 * Get the current user
761 * @return \BookStack\Auth\User
763 private function currentUser()
765 if ($this->currentUserModel === false) {
766 $this->currentUserModel = user();
769 return $this->currentUserModel;
773 * Clean the cached user elements.
775 private function clean()
777 $this->currentUserModel = false;
778 $this->userRoles = false;
779 $this->isAdminUser = null;