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 BookStack\Traits\HasCreatorAndUpdater;
10 use BookStack\Traits\HasOwner;
11 use Illuminate\Database\Connection;
12 use Illuminate\Database\Eloquent\Builder;
13 use Illuminate\Database\Query\Builder as QueryBuilder;
14 use Illuminate\Support\Collection;
16 class PermissionService
19 protected $currentAction;
20 protected $isAdminUser;
21 protected $userRoles = false;
22 protected $currentUserModel = false;
30 * @var JointPermission
32 protected $jointPermission;
40 * @var EntityPermission
42 protected $entityPermission;
47 protected $entityProvider;
49 protected $entityCache;
52 * PermissionService constructor.
54 public function __construct(
55 JointPermission $jointPermission,
56 Permissions\EntityPermission $entityPermission,
59 EntityProvider $entityProvider
62 $this->jointPermission = $jointPermission;
63 $this->entityPermission = $entityPermission;
65 $this->entityProvider = $entityProvider;
69 * Set the database connection
70 * @param Connection $connection
72 public function setConnection(Connection $connection)
74 $this->db = $connection;
78 * Prepare the local entity cache and ensure it's empty
79 * @param \BookStack\Entities\Models\Entity[] $entities
81 protected function readyEntityCache($entities = [])
83 $this->entityCache = [];
85 foreach ($entities as $entity) {
86 $type = $entity->getType();
87 if (!isset($this->entityCache[$type])) {
88 $this->entityCache[$type] = collect();
90 $this->entityCache[$type]->put($entity->id, $entity);
95 * Get a book via ID, Checks local cache
99 protected function getBook($bookId)
101 if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
102 return $this->entityCache['book']->get($bookId);
105 $book = $this->entityProvider->book->find($bookId);
106 if ($book === null) {
114 * Get a chapter via ID, Checks local cache
116 * @return \BookStack\Entities\Models\Book
118 protected function getChapter($chapterId)
120 if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
121 return $this->entityCache['chapter']->get($chapterId);
124 $chapter = $this->entityProvider->chapter->find($chapterId);
125 if ($chapter === null) {
133 * Get the roles for the current user;
136 protected function getRoles()
138 if ($this->userRoles !== false) {
139 return $this->userRoles;
144 if (auth()->guest()) {
145 $roles[] = $this->role->getSystemRole('public')->id;
150 foreach ($this->currentUser()->roles as $role) {
151 $roles[] = $role->id;
157 * Re-generate all entity permission from scratch.
159 public function buildJointPermissions()
161 $this->jointPermission->truncate();
162 $this->readyEntityCache();
164 // Get all roles (Should be the most limited dimension)
165 $roles = $this->role->with('permissions')->get()->all();
167 // Chunk through all books
168 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
169 $this->buildJointPermissionsForBooks($books, $roles);
172 // Chunk through all bookshelves
173 $this->entityProvider->bookshelf->newQuery()->withTrashed()->select(['id', 'restricted', 'owned_by'])
174 ->chunk(50, function ($shelves) use ($roles) {
175 $this->buildJointPermissionsForShelves($shelves, $roles);
180 * Get a query for fetching a book with it's children.
181 * @return QueryBuilder
183 protected function bookFetchQuery()
185 return $this->entityProvider->book->withTrashed()->newQuery()
186 ->select(['id', 'restricted', 'owned_by'])->with(['chapters' => function ($query) {
187 $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id']);
188 }, 'pages' => function ($query) {
189 $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']);
194 * @param Collection $shelves
195 * @param array $roles
196 * @param bool $deleteOld
199 protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false)
202 $this->deleteManyJointPermissionsForEntities($shelves->all());
204 $this->createManyJointPermissions($shelves, $roles);
208 * Build joint permissions for an array of books
209 * @param Collection $books
210 * @param array $roles
211 * @param bool $deleteOld
213 protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
215 $entities = clone $books;
217 /** @var Book $book */
218 foreach ($books->all() as $book) {
219 foreach ($book->getRelation('chapters') as $chapter) {
220 $entities->push($chapter);
222 foreach ($book->getRelation('pages') as $page) {
223 $entities->push($page);
228 $this->deleteManyJointPermissionsForEntities($entities->all());
230 $this->createManyJointPermissions($entities, $roles);
234 * Rebuild the entity jointPermissions for a particular entity.
235 * @param \BookStack\Entities\Models\Entity $entity
238 public function buildJointPermissionsForEntity(Entity $entity)
240 $entities = [$entity];
241 if ($entity->isA('book')) {
242 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
243 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
248 $entities[] = $entity->book;
251 if ($entity->isA('page') && $entity->chapter_id) {
252 $entities[] = $entity->chapter;
255 if ($entity->isA('chapter')) {
256 foreach ($entity->pages as $page) {
261 $this->buildJointPermissionsForEntities(collect($entities));
265 * Rebuild the entity jointPermissions for a collection of entities.
266 * @param Collection $entities
269 public function buildJointPermissionsForEntities(Collection $entities)
271 $roles = $this->role->newQuery()->get();
272 $this->deleteManyJointPermissionsForEntities($entities->all());
273 $this->createManyJointPermissions($entities, $roles);
277 * Build the entity jointPermissions for a particular role.
280 public function buildJointPermissionForRole(Role $role)
283 $this->deleteManyJointPermissionsForRoles($roles);
285 // Chunk through all books
286 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
287 $this->buildJointPermissionsForBooks($books, $roles);
290 // Chunk through all bookshelves
291 $this->entityProvider->bookshelf->newQuery()->select(['id', 'restricted', 'owned_by'])
292 ->chunk(50, function ($shelves) use ($roles) {
293 $this->buildJointPermissionsForShelves($shelves, $roles);
298 * Delete the entity jointPermissions attached to a particular role.
301 public function deleteJointPermissionsForRole(Role $role)
303 $this->deleteManyJointPermissionsForRoles([$role]);
307 * Delete all of the entity jointPermissions for a list of entities.
308 * @param Role[] $roles
310 protected function deleteManyJointPermissionsForRoles($roles)
312 $roleIds = array_map(function ($role) {
315 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
319 * Delete the entity jointPermissions for a particular entity.
320 * @param Entity $entity
323 public function deleteJointPermissionsForEntity(Entity $entity)
325 $this->deleteManyJointPermissionsForEntities([$entity]);
329 * Delete all of the entity jointPermissions for a list of entities.
330 * @param \BookStack\Entities\Models\Entity[] $entities
333 protected function deleteManyJointPermissionsForEntities($entities)
335 if (count($entities) === 0) {
339 $this->db->transaction(function () use ($entities) {
341 foreach (array_chunk($entities, 1000) as $entityChunk) {
342 $query = $this->db->table('joint_permissions');
343 foreach ($entityChunk as $entity) {
344 $query->orWhere(function (QueryBuilder $query) use ($entity) {
345 $query->where('entity_id', '=', $entity->id)
346 ->where('entity_type', '=', $entity->getMorphClass());
355 * Create & Save entity jointPermissions for many entities and jointPermissions.
356 * @param Collection $entities
357 * @param array $roles
360 protected function createManyJointPermissions($entities, $roles)
362 $this->readyEntityCache($entities);
363 $jointPermissions = [];
365 // Fetch Entity Permissions and create a mapping of entity restricted statuses
366 $entityRestrictedMap = [];
367 $permissionFetch = $this->entityPermission->newQuery();
368 foreach ($entities as $entity) {
369 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
370 $permissionFetch->orWhere(function ($query) use ($entity) {
371 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
374 $permissions = $permissionFetch->get();
376 // Create a mapping of explicit entity permissions
378 foreach ($permissions as $permission) {
379 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
380 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
381 $permissionMap[$key] = $isRestricted;
384 // Create a mapping of role permissions
385 $rolePermissionMap = [];
386 foreach ($roles as $role) {
387 foreach ($role->permissions as $permission) {
388 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
392 // Create Joint Permission Data
393 foreach ($entities as $entity) {
394 foreach ($roles as $role) {
395 foreach ($this->getActions($entity) as $action) {
396 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
401 $this->db->transaction(function () use ($jointPermissions) {
402 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
403 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
410 * Get the actions related to an entity.
411 * @param \BookStack\Entities\Models\Entity $entity
414 protected function getActions(Entity $entity)
416 $baseActions = ['view', 'update', 'delete'];
417 if ($entity->isA('chapter') || $entity->isA('book')) {
418 $baseActions[] = 'page-create';
420 if ($entity->isA('book')) {
421 $baseActions[] = 'chapter-create';
427 * Create entity permission data for an entity and role
428 * for a particular action.
429 * @param Entity $entity
431 * @param string $action
432 * @param array $permissionMap
433 * @param array $rolePermissionMap
436 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
438 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
439 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
440 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
441 $explodedAction = explode('-', $action);
442 $restrictionAction = end($explodedAction);
444 if ($role->system_name === 'admin') {
445 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
448 if ($entity->restricted) {
449 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
450 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
453 if ($entity->isA('book') || $entity->isA('bookshelf')) {
454 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
457 // For chapters and pages, Check if explicit permissions are set on the Book.
458 $book = $this->getBook($entity->book_id);
459 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
460 $hasPermissiveAccessToParents = !$book->restricted;
462 // For pages with a chapter, Check if explicit permissions are set on the Chapter
463 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
464 $chapter = $this->getChapter($entity->chapter_id);
465 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
466 if ($chapter->restricted) {
467 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
471 return $this->createJointPermissionDataArray(
475 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
476 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
481 * Check for an active restriction in an entity map.
483 * @param Entity $entity
488 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
490 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
491 return isset($entityMap[$key]) ? $entityMap[$key] : false;
495 * Create an array of data with the information of an entity jointPermissions.
496 * Used to build data for bulk insertion.
497 * @param \BookStack\Entities\Models\Entity $entity
500 * @param $permissionAll
501 * @param $permissionOwn
504 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
507 'role_id' => $role->getRawAttribute('id'),
508 'entity_id' => $entity->getRawAttribute('id'),
509 'entity_type' => $entity->getMorphClass(),
511 'has_permission' => $permissionAll,
512 'has_permission_own' => $permissionOwn,
513 'owned_by' => $entity->getRawAttribute('owned_by')
518 * Checks if an entity has a restriction set upon it.
519 * @param HasCreatorAndUpdater|HasOwner $ownable
521 public function checkOwnableUserAccess(Model $ownable, string $permission): bool
523 $explodedPermission = explode('-', $permission);
525 $baseQuery = $ownable->newQuery()->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 $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
537 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->$ownerField;
538 return ($allPermission || ($isOwner && $ownPermission));
541 // Handle abnormal create jointPermissions
542 if ($action === 'create') {
543 $this->currentAction = $permission;
546 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
552 * Checks if a user has the given permission for any items in the system.
553 * Can be passed an entity instance to filter on a specific type.
554 * @param string $permission
555 * @param string $entityClass
558 public function checkUserHasPermissionOnAnything(string $permission, string $entityClass = null)
560 $userRoleIds = $this->currentUser()->roles()->select('id')->pluck('id')->toArray();
561 $userId = $this->currentUser()->id;
563 $permissionQuery = $this->db->table('joint_permissions')
564 ->where('action', '=', $permission)
565 ->whereIn('role_id', $userRoleIds)
566 ->where(function ($query) use ($userId) {
567 $query->where('has_permission', '=', 1)
568 ->orWhere(function ($query2) use ($userId) {
569 $query2->where('has_permission_own', '=', 1)
570 ->where('owned_by', '=', $userId);
574 if (!is_null($entityClass)) {
575 $entityInstance = app()->make($entityClass);
576 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
579 $hasPermission = $permissionQuery->count() > 0;
581 return $hasPermission;
585 * Check if an entity has restrictions set on itself or its
587 * @param \BookStack\Entities\Models\Entity $entity
591 public function checkIfRestrictionsSet(Entity $entity, $action)
593 $this->currentAction = $action;
594 if ($entity->isA('page')) {
595 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
596 } elseif ($entity->isA('chapter')) {
597 return $entity->restricted || $entity->book->restricted;
598 } elseif ($entity->isA('book')) {
599 return $entity->restricted;
604 * The general query filter to remove all entities
605 * that the current user does not have access to.
609 protected function entityRestrictionQuery($query)
611 $q = $query->where(function ($parentQuery) {
612 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
613 $permissionQuery->whereIn('role_id', $this->getRoles())
614 ->where('action', '=', $this->currentAction)
615 ->where(function ($query) {
616 $query->where('has_permission', '=', true)
617 ->orWhere(function ($query) {
618 $query->where('has_permission_own', '=', true)
619 ->where('owned_by', '=', $this->currentUser()->id);
629 * Limited the given entity query so that the query will only
630 * return items that the user has permission for the given ability.
632 public function restrictEntityQuery(Builder $query, string $ability = 'view'): Builder
635 return $query->where(function (Builder $parentQuery) use ($ability) {
636 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) use ($ability) {
637 $permissionQuery->whereIn('role_id', $this->getRoles())
638 ->where('action', '=', $ability)
639 ->where(function (Builder $query) {
640 $query->where('has_permission', '=', true)
641 ->orWhere(function (Builder $query) {
642 $query->where('has_permission_own', '=', true)
643 ->where('owned_by', '=', $this->currentUser()->id);
651 * Extend the given page query to ensure draft items are not visible
652 * unless created by the given user.
654 public function enforceDraftVisiblityOnQuery(Builder $query): Builder
656 return $query->where(function (Builder $query) {
657 $query->where('draft', '=', false)
658 ->orWhere(function (Builder $query) {
659 $query->where('draft', '=', true)
660 ->where('owned_by', '=', $this->currentUser()->id);
666 * Add restrictions for a generic entity
667 * @param string $entityType
668 * @param Builder|\BookStack\Entities\Models\Entity $query
669 * @param string $action
672 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
674 if (strtolower($entityType) === 'page') {
675 // Prevent drafts being visible to others.
676 $query = $query->where(function ($query) {
677 $query->where('draft', '=', false)
678 ->orWhere(function ($query) {
679 $query->where('draft', '=', true)
680 ->where('owned_by', '=', $this->currentUser()->id);
685 $this->currentAction = $action;
686 return $this->entityRestrictionQuery($query);
690 * Filter items that have entities set as a polymorphic relation.
692 * @param string $tableName
693 * @param string $entityIdColumn
694 * @param string $entityTypeColumn
695 * @param string $action
696 * @return QueryBuilder
698 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
701 $this->currentAction = $action;
702 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
704 $q = $query->where(function ($query) use ($tableDetails) {
705 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
706 $permissionQuery->select('id')->from('joint_permissions')
707 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
708 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
709 ->where('action', '=', $this->currentAction)
710 ->whereIn('role_id', $this->getRoles())
711 ->where(function ($query) {
712 $query->where('has_permission', '=', true)->orWhere(function ($query) {
713 $query->where('has_permission_own', '=', true)
714 ->where('owned_by', '=', $this->currentUser()->id);
724 * Add conditions to a query to filter the selection to related entities
725 * where permissions are granted.
729 * @param $entityIdColumn
732 public function filterRelatedEntity($entityType, $query, $tableName, $entityIdColumn)
734 $this->currentAction = 'view';
735 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
737 $pageMorphClass = $this->entityProvider->get($entityType)->getMorphClass();
739 $q = $query->where(function ($query) use ($tableDetails, $pageMorphClass) {
740 $query->where(function ($query) use (&$tableDetails, $pageMorphClass) {
741 $query->whereExists(function ($permissionQuery) use (&$tableDetails, $pageMorphClass) {
742 $permissionQuery->select('id')->from('joint_permissions')
743 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
744 ->where('entity_type', '=', $pageMorphClass)
745 ->where('action', '=', $this->currentAction)
746 ->whereIn('role_id', $this->getRoles())
747 ->where(function ($query) {
748 $query->where('has_permission', '=', true)->orWhere(function ($query) {
749 $query->where('has_permission_own', '=', true)
750 ->where('owned_by', '=', $this->currentUser()->id);
754 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
763 * Get the current user
764 * @return \BookStack\Auth\User
766 private function currentUser()
768 if ($this->currentUserModel === false) {
769 $this->currentUserModel = user();
772 return $this->currentUserModel;
776 * Clean the cached user elements.
778 private function clean()
780 $this->currentUserModel = false;
781 $this->userRoles = false;
782 $this->isAdminUser = null;