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\Entity;
7 use BookStack\Entities\EntityProvider;
9 use Illuminate\Database\Connection;
10 use Illuminate\Database\Eloquent\Builder;
11 use Illuminate\Database\Query\Builder as QueryBuilder;
12 use Illuminate\Support\Collection;
14 class PermissionService
17 protected $currentAction;
18 protected $isAdminUser;
19 protected $userRoles = false;
20 protected $currentUserModel = false;
28 * @var JointPermission
30 protected $jointPermission;
38 * @var EntityPermission
40 protected $entityPermission;
45 protected $entityProvider;
47 protected $entityCache;
50 * PermissionService constructor.
52 public function __construct(
53 JointPermission $jointPermission,
54 Permissions\EntityPermission $entityPermission,
57 EntityProvider $entityProvider
60 $this->jointPermission = $jointPermission;
61 $this->entityPermission = $entityPermission;
63 $this->entityProvider = $entityProvider;
67 * Set the database connection
68 * @param Connection $connection
70 public function setConnection(Connection $connection)
72 $this->db = $connection;
76 * Prepare the local entity cache and ensure it's empty
77 * @param \BookStack\Entities\Models\Entity[] $entities
79 protected function readyEntityCache($entities = [])
81 $this->entityCache = [];
83 foreach ($entities as $entity) {
84 $type = $entity->getType();
85 if (!isset($this->entityCache[$type])) {
86 $this->entityCache[$type] = collect();
88 $this->entityCache[$type]->put($entity->id, $entity);
93 * Get a book via ID, Checks local cache
97 protected function getBook($bookId)
99 if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
100 return $this->entityCache['book']->get($bookId);
103 $book = $this->entityProvider->book->find($bookId);
104 if ($book === null) {
112 * Get a chapter via ID, Checks local cache
114 * @return \BookStack\Entities\Models\Book
116 protected function getChapter($chapterId)
118 if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
119 return $this->entityCache['chapter']->get($chapterId);
122 $chapter = $this->entityProvider->chapter->find($chapterId);
123 if ($chapter === null) {
131 * Get the roles for the current user;
134 protected function getRoles()
136 if ($this->userRoles !== false) {
137 return $this->userRoles;
142 if (auth()->guest()) {
143 $roles[] = $this->role->getSystemRole('public')->id;
148 foreach ($this->currentUser()->roles as $role) {
149 $roles[] = $role->id;
155 * Re-generate all entity permission from scratch.
157 public function buildJointPermissions()
159 $this->jointPermission->truncate();
160 $this->readyEntityCache();
162 // Get all roles (Should be the most limited dimension)
163 $roles = $this->role->with('permissions')->get()->all();
165 // Chunk through all books
166 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
167 $this->buildJointPermissionsForBooks($books, $roles);
170 // Chunk through all bookshelves
171 $this->entityProvider->bookshelf->newQuery()->withTrashed()->select(['id', 'restricted', 'created_by'])
172 ->chunk(50, function ($shelves) use ($roles) {
173 $this->buildJointPermissionsForShelves($shelves, $roles);
178 * Get a query for fetching a book with it's children.
179 * @return QueryBuilder
181 protected function bookFetchQuery()
183 return $this->entityProvider->book->withTrashed()->newQuery()
184 ->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
185 $query->withTrashed()->select(['id', 'restricted', 'created_by', 'book_id']);
186 }, 'pages' => function ($query) {
187 $query->withTrashed()->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
192 * @param Collection $shelves
193 * @param array $roles
194 * @param bool $deleteOld
197 protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false)
200 $this->deleteManyJointPermissionsForEntities($shelves->all());
202 $this->createManyJointPermissions($shelves, $roles);
206 * Build joint permissions for an array of books
207 * @param Collection $books
208 * @param array $roles
209 * @param bool $deleteOld
211 protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
213 $entities = clone $books;
215 /** @var Book $book */
216 foreach ($books->all() as $book) {
217 foreach ($book->getRelation('chapters') as $chapter) {
218 $entities->push($chapter);
220 foreach ($book->getRelation('pages') as $page) {
221 $entities->push($page);
226 $this->deleteManyJointPermissionsForEntities($entities->all());
228 $this->createManyJointPermissions($entities, $roles);
232 * Rebuild the entity jointPermissions for a particular entity.
233 * @param \BookStack\Entities\Models\Entity $entity
236 public function buildJointPermissionsForEntity(Entity $entity)
238 $entities = [$entity];
239 if ($entity->isA('book')) {
240 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
241 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
246 $entities[] = $entity->book;
249 if ($entity->isA('page') && $entity->chapter_id) {
250 $entities[] = $entity->chapter;
253 if ($entity->isA('chapter')) {
254 foreach ($entity->pages as $page) {
259 $this->buildJointPermissionsForEntities(collect($entities));
263 * Rebuild the entity jointPermissions for a collection of entities.
264 * @param Collection $entities
267 public function buildJointPermissionsForEntities(Collection $entities)
269 $roles = $this->role->newQuery()->get();
270 $this->deleteManyJointPermissionsForEntities($entities->all());
271 $this->createManyJointPermissions($entities, $roles);
275 * Build the entity jointPermissions for a particular role.
278 public function buildJointPermissionForRole(Role $role)
281 $this->deleteManyJointPermissionsForRoles($roles);
283 // Chunk through all books
284 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
285 $this->buildJointPermissionsForBooks($books, $roles);
288 // Chunk through all bookshelves
289 $this->entityProvider->bookshelf->newQuery()->select(['id', 'restricted', 'created_by'])
290 ->chunk(50, function ($shelves) use ($roles) {
291 $this->buildJointPermissionsForShelves($shelves, $roles);
296 * Delete the entity jointPermissions attached to a particular role.
299 public function deleteJointPermissionsForRole(Role $role)
301 $this->deleteManyJointPermissionsForRoles([$role]);
305 * Delete all of the entity jointPermissions for a list of entities.
306 * @param Role[] $roles
308 protected function deleteManyJointPermissionsForRoles($roles)
310 $roleIds = array_map(function ($role) {
313 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
317 * Delete the entity jointPermissions for a particular entity.
318 * @param Entity $entity
321 public function deleteJointPermissionsForEntity(Entity $entity)
323 $this->deleteManyJointPermissionsForEntities([$entity]);
327 * Delete all of the entity jointPermissions for a list of entities.
328 * @param \BookStack\Entities\Models\Entity[] $entities
331 protected function deleteManyJointPermissionsForEntities($entities)
333 if (count($entities) === 0) {
337 $this->db->transaction(function () use ($entities) {
339 foreach (array_chunk($entities, 1000) as $entityChunk) {
340 $query = $this->db->table('joint_permissions');
341 foreach ($entityChunk as $entity) {
342 $query->orWhere(function (QueryBuilder $query) use ($entity) {
343 $query->where('entity_id', '=', $entity->id)
344 ->where('entity_type', '=', $entity->getMorphClass());
353 * Create & Save entity jointPermissions for many entities and jointPermissions.
354 * @param Collection $entities
355 * @param array $roles
358 protected function createManyJointPermissions($entities, $roles)
360 $this->readyEntityCache($entities);
361 $jointPermissions = [];
363 // Fetch Entity Permissions and create a mapping of entity restricted statuses
364 $entityRestrictedMap = [];
365 $permissionFetch = $this->entityPermission->newQuery();
366 foreach ($entities as $entity) {
367 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
368 $permissionFetch->orWhere(function ($query) use ($entity) {
369 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
372 $permissions = $permissionFetch->get();
374 // Create a mapping of explicit entity permissions
376 foreach ($permissions as $permission) {
377 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
378 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
379 $permissionMap[$key] = $isRestricted;
382 // Create a mapping of role permissions
383 $rolePermissionMap = [];
384 foreach ($roles as $role) {
385 foreach ($role->permissions as $permission) {
386 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
390 // Create Joint Permission Data
391 foreach ($entities as $entity) {
392 foreach ($roles as $role) {
393 foreach ($this->getActions($entity) as $action) {
394 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
399 $this->db->transaction(function () use ($jointPermissions) {
400 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
401 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
408 * Get the actions related to an entity.
409 * @param \BookStack\Entities\Models\Entity $entity
412 protected function getActions(Entity $entity)
414 $baseActions = ['view', 'update', 'delete'];
415 if ($entity->isA('chapter') || $entity->isA('book')) {
416 $baseActions[] = 'page-create';
418 if ($entity->isA('book')) {
419 $baseActions[] = 'chapter-create';
425 * Create entity permission data for an entity and role
426 * for a particular action.
427 * @param Entity $entity
429 * @param string $action
430 * @param array $permissionMap
431 * @param array $rolePermissionMap
434 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
436 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
437 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
438 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
439 $explodedAction = explode('-', $action);
440 $restrictionAction = end($explodedAction);
442 if ($role->system_name === 'admin') {
443 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
446 if ($entity->restricted) {
447 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
448 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
451 if ($entity->isA('book') || $entity->isA('bookshelf')) {
452 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
455 // For chapters and pages, Check if explicit permissions are set on the Book.
456 $book = $this->getBook($entity->book_id);
457 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
458 $hasPermissiveAccessToParents = !$book->restricted;
460 // For pages with a chapter, Check if explicit permissions are set on the Chapter
461 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
462 $chapter = $this->getChapter($entity->chapter_id);
463 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
464 if ($chapter->restricted) {
465 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
469 return $this->createJointPermissionDataArray(
473 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
474 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
479 * Check for an active restriction in an entity map.
481 * @param Entity $entity
486 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
488 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
489 return isset($entityMap[$key]) ? $entityMap[$key] : false;
493 * Create an array of data with the information of an entity jointPermissions.
494 * Used to build data for bulk insertion.
495 * @param \BookStack\Entities\Models\Entity $entity
498 * @param $permissionAll
499 * @param $permissionOwn
502 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
505 'role_id' => $role->getRawAttribute('id'),
506 'entity_id' => $entity->getRawAttribute('id'),
507 'entity_type' => $entity->getMorphClass(),
509 'has_permission' => $permissionAll,
510 'has_permission_own' => $permissionOwn,
511 'created_by' => $entity->getRawAttribute('created_by')
516 * Checks if an entity has a restriction set upon it.
517 * @param Ownable $ownable
521 public function checkOwnableUserAccess(Ownable $ownable, $permission)
523 $explodedPermission = explode('-', $permission);
525 $baseQuery = $ownable->where('id', '=', $ownable->id);
526 $action = end($explodedPermission);
527 $this->currentAction = $action;
529 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
531 // Handle non entity specific jointPermissions
532 if (in_array($explodedPermission[0], $nonJointPermissions)) {
533 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
534 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
535 $this->currentAction = 'view';
536 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
537 return ($allPermission || ($isOwner && $ownPermission));
540 // Handle abnormal create jointPermissions
541 if ($action === 'create') {
542 $this->currentAction = $permission;
545 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
551 * Checks if a user has the given permission for any items in the system.
552 * Can be passed an entity instance to filter on a specific type.
553 * @param string $permission
554 * @param string $entityClass
557 public function checkUserHasPermissionOnAnything(string $permission, string $entityClass = null)
559 $userRoleIds = $this->currentUser()->roles()->select('id')->pluck('id')->toArray();
560 $userId = $this->currentUser()->id;
562 $permissionQuery = $this->db->table('joint_permissions')
563 ->where('action', '=', $permission)
564 ->whereIn('role_id', $userRoleIds)
565 ->where(function ($query) use ($userId) {
566 $query->where('has_permission', '=', 1)
567 ->orWhere(function ($query2) use ($userId) {
568 $query2->where('has_permission_own', '=', 1)
569 ->where('created_by', '=', $userId);
573 if (!is_null($entityClass)) {
574 $entityInstance = app()->make($entityClass);
575 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
578 $hasPermission = $permissionQuery->count() > 0;
580 return $hasPermission;
584 * Check if an entity has restrictions set on itself or its
586 * @param \BookStack\Entities\Models\Entity $entity
590 public function checkIfRestrictionsSet(Entity $entity, $action)
592 $this->currentAction = $action;
593 if ($entity->isA('page')) {
594 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
595 } elseif ($entity->isA('chapter')) {
596 return $entity->restricted || $entity->book->restricted;
597 } elseif ($entity->isA('book')) {
598 return $entity->restricted;
603 * The general query filter to remove all entities
604 * that the current user does not have access to.
608 protected function entityRestrictionQuery($query)
610 $q = $query->where(function ($parentQuery) {
611 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
612 $permissionQuery->whereIn('role_id', $this->getRoles())
613 ->where('action', '=', $this->currentAction)
614 ->where(function ($query) {
615 $query->where('has_permission', '=', true)
616 ->orWhere(function ($query) {
617 $query->where('has_permission_own', '=', true)
618 ->where('created_by', '=', $this->currentUser()->id);
628 * Limited the given entity query so that the query will only
629 * return items that the user has permission for the given ability.
631 public function restrictEntityQuery(Builder $query, string $ability = 'view'): Builder
634 return $query->where(function (Builder $parentQuery) use ($ability) {
635 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) use ($ability) {
636 $permissionQuery->whereIn('role_id', $this->getRoles())
637 ->where('action', '=', $ability)
638 ->where(function (Builder $query) {
639 $query->where('has_permission', '=', true)
640 ->orWhere(function (Builder $query) {
641 $query->where('has_permission_own', '=', true)
642 ->where('created_by', '=', $this->currentUser()->id);
650 * Extend the given page query to ensure draft items are not visible
651 * unless created by the given user.
653 public function enforceDraftVisiblityOnQuery(Builder $query): Builder
655 return $query->where(function (Builder $query) {
656 $query->where('draft', '=', false)
657 ->orWhere(function (Builder $query) {
658 $query->where('draft', '=', true)
659 ->where('created_by', '=', $this->currentUser()->id);
665 * Add restrictions for a generic entity
666 * @param string $entityType
667 * @param Builder|\BookStack\Entities\Models\Entity $query
668 * @param string $action
671 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
673 if (strtolower($entityType) === 'page') {
674 // Prevent drafts being visible to others.
675 $query = $query->where(function ($query) {
676 $query->where('draft', '=', false)
677 ->orWhere(function ($query) {
678 $query->where('draft', '=', true)
679 ->where('created_by', '=', $this->currentUser()->id);
684 $this->currentAction = $action;
685 return $this->entityRestrictionQuery($query);
689 * Filter items that have entities set as a polymorphic relation.
691 * @param string $tableName
692 * @param string $entityIdColumn
693 * @param string $entityTypeColumn
694 * @param string $action
695 * @return QueryBuilder
697 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
700 $this->currentAction = $action;
701 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
703 $q = $query->where(function ($query) use ($tableDetails) {
704 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
705 $permissionQuery->select('id')->from('joint_permissions')
706 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
707 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
708 ->where('action', '=', $this->currentAction)
709 ->whereIn('role_id', $this->getRoles())
710 ->where(function ($query) {
711 $query->where('has_permission', '=', true)->orWhere(function ($query) {
712 $query->where('has_permission_own', '=', true)
713 ->where('created_by', '=', $this->currentUser()->id);
723 * Add conditions to a query to filter the selection to related entities
724 * where permissions are granted.
728 * @param $entityIdColumn
731 public function filterRelatedEntity($entityType, $query, $tableName, $entityIdColumn)
733 $this->currentAction = 'view';
734 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
736 $pageMorphClass = $this->entityProvider->get($entityType)->getMorphClass();
738 $q = $query->where(function ($query) use ($tableDetails, $pageMorphClass) {
739 $query->where(function ($query) use (&$tableDetails, $pageMorphClass) {
740 $query->whereExists(function ($permissionQuery) use (&$tableDetails, $pageMorphClass) {
741 $permissionQuery->select('id')->from('joint_permissions')
742 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
743 ->where('entity_type', '=', $pageMorphClass)
744 ->where('action', '=', $this->currentAction)
745 ->whereIn('role_id', $this->getRoles())
746 ->where(function ($query) {
747 $query->where('has_permission', '=', true)->orWhere(function ($query) {
748 $query->where('has_permission_own', '=', true)
749 ->where('created_by', '=', $this->currentUser()->id);
753 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
762 * Get the current user
763 * @return \BookStack\Auth\User
765 private function currentUser()
767 if ($this->currentUserModel === false) {
768 $this->currentUserModel = user();
771 return $this->currentUserModel;
775 * Clean the cached user elements.
777 private function clean()
779 $this->currentUserModel = false;
780 $this->userRoles = false;
781 $this->isAdminUser = null;