X-Git-Url: http://source.bookstackapp.com/bookstack/blobdiff_plain/a6633642232efd164d4708967ab59e498fbff896..refs/pull/3365/head:/app/Auth/Permissions/PermissionService.php diff --git a/app/Auth/Permissions/PermissionService.php b/app/Auth/Permissions/PermissionService.php index 89c8a5fbb..59ff37dc9 100644 --- a/app/Auth/Permissions/PermissionService.php +++ b/app/Auth/Permissions/PermissionService.php @@ -1,73 +1,56 @@ -db = $db; - $this->jointPermission = $jointPermission; - $this->entityPermission = $entityPermission; - $this->role = $role; - $this->entityProvider = $entityProvider; } /** - * Set the database connection - * @param Connection $connection + * Set the database connection. */ public function setConnection(Connection $connection) { @@ -75,82 +58,65 @@ class PermissionService } /** - * Prepare the local entity cache and ensure it's empty - * @param \BookStack\Entities\Models\Entity[] $entities + * Prepare the local entity cache and ensure it's empty. + * + * @param Entity[] $entities */ - protected function readyEntityCache($entities = []) + protected function readyEntityCache(array $entities = []) { $this->entityCache = []; foreach ($entities as $entity) { - $type = $entity->getType(); - if (!isset($this->entityCache[$type])) { - $this->entityCache[$type] = collect(); + $class = get_class($entity); + if (!isset($this->entityCache[$class])) { + $this->entityCache[$class] = collect(); } - $this->entityCache[$type]->put($entity->id, $entity); + $this->entityCache[$class]->put($entity->id, $entity); } } /** - * Get a book via ID, Checks local cache - * @param $bookId - * @return Book + * Get a book via ID, Checks local cache. */ - protected function getBook($bookId) + protected function getBook(int $bookId): ?Book { - if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) { - return $this->entityCache['book']->get($bookId); - } - - $book = $this->entityProvider->book->find($bookId); - if ($book === null) { - $book = false; + if (isset($this->entityCache[Book::class]) && $this->entityCache[Book::class]->has($bookId)) { + return $this->entityCache[Book::class]->get($bookId); } - return $book; + return Book::query()->withTrashed()->find($bookId); } /** - * Get a chapter via ID, Checks local cache - * @param $chapterId - * @return \BookStack\Entities\Models\Book + * Get a chapter via ID, Checks local cache. */ - protected function getChapter($chapterId) + protected function getChapter(int $chapterId): ?Chapter { - if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) { - return $this->entityCache['chapter']->get($chapterId); - } - - $chapter = $this->entityProvider->chapter->find($chapterId); - if ($chapter === null) { - $chapter = false; + if (isset($this->entityCache[Chapter::class]) && $this->entityCache[Chapter::class]->has($chapterId)) { + return $this->entityCache[Chapter::class]->get($chapterId); } - return $chapter; + return Chapter::query() + ->withTrashed() + ->find($chapterId); } /** - * Get the roles for the current user; - * @return array|bool + * Get the roles for the current logged in user. */ - protected function getRoles() + protected function getCurrentUserRoles(): array { - if ($this->userRoles !== false) { + if (!is_null($this->userRoles)) { return $this->userRoles; } - $roles = []; - if (auth()->guest()) { - $roles[] = $this->role->getSystemRole('public')->id; - return $roles; + $this->userRoles = [Role::getSystemRole('public')->id]; + } else { + $this->userRoles = $this->currentUser()->roles->pluck('id')->values()->all(); } - - foreach ($this->currentUser()->roles as $role) { - $roles[] = $role->id; - } - return $roles; + return $this->userRoles; } /** @@ -158,59 +124,59 @@ class PermissionService */ public function buildJointPermissions() { - $this->jointPermission->truncate(); + JointPermission::query()->truncate(); $this->readyEntityCache(); // Get all roles (Should be the most limited dimension) - $roles = $this->role->with('permissions')->get()->all(); + $roles = Role::query()->with('permissions')->get()->all(); // Chunk through all books - $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) { + $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) { $this->buildJointPermissionsForBooks($books, $roles); }); // Chunk through all bookshelves - $this->entityProvider->bookshelf->newQuery()->withTrashed()->select(['id', 'restricted', 'owned_by']) - ->chunk(50, function ($shelves) use ($roles) { + Bookshelf::query()->withTrashed()->select(['id', 'restricted', 'owned_by']) + ->chunk(50, function (EloquentCollection $shelves) use ($roles) { $this->buildJointPermissionsForShelves($shelves, $roles); }); } /** * Get a query for fetching a book with it's children. - * @return QueryBuilder */ - protected function bookFetchQuery() + protected function bookFetchQuery(): Builder { - return $this->entityProvider->book->withTrashed()->newQuery() - ->select(['id', 'restricted', 'owned_by'])->with(['chapters' => function ($query) { - $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id']); - }, 'pages' => function ($query) { - $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']); - }]); + return Book::query()->withTrashed() + ->select(['id', 'restricted', 'owned_by'])->with([ + 'chapters' => function ($query) { + $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id']); + }, + 'pages' => function ($query) { + $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']); + }, + ]); } /** - * @param Collection $shelves - * @param array $roles - * @param bool $deleteOld - * @throws \Throwable + * Build joint permissions for the given shelf and role combinations. + * + * @throws Throwable */ - protected function buildJointPermissionsForShelves($shelves, $roles, $deleteOld = false) + protected function buildJointPermissionsForShelves(EloquentCollection $shelves, array $roles, bool $deleteOld = false) { if ($deleteOld) { $this->deleteManyJointPermissionsForEntities($shelves->all()); } - $this->createManyJointPermissions($shelves, $roles); + $this->createManyJointPermissions($shelves->all(), $roles); } /** - * Build joint permissions for an array of books - * @param Collection $books - * @param array $roles - * @param bool $deleteOld + * Build joint permissions for the given book and role combinations. + * + * @throws Throwable */ - protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false) + protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false) { $entities = clone $books; @@ -227,55 +193,56 @@ class PermissionService if ($deleteOld) { $this->deleteManyJointPermissionsForEntities($entities->all()); } - $this->createManyJointPermissions($entities, $roles); + $this->createManyJointPermissions($entities->all(), $roles); } /** * Rebuild the entity jointPermissions for a particular entity. - * @param \BookStack\Entities\Models\Entity $entity - * @throws \Throwable + * + * @throws Throwable */ public function buildJointPermissionsForEntity(Entity $entity) { $entities = [$entity]; - if ($entity->isA('book')) { + if ($entity instanceof Book) { $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get(); - $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true); + $this->buildJointPermissionsForBooks($books, Role::query()->get()->all(), true); + return; } + /** @var BookChild $entity */ if ($entity->book) { $entities[] = $entity->book; } - if ($entity->isA('page') && $entity->chapter_id) { + if ($entity instanceof Page && $entity->chapter_id) { $entities[] = $entity->chapter; } - if ($entity->isA('chapter')) { + if ($entity instanceof Chapter) { foreach ($entity->pages as $page) { $entities[] = $page; } } - $this->buildJointPermissionsForEntities(collect($entities)); + $this->buildJointPermissionsForEntities($entities); } /** * Rebuild the entity jointPermissions for a collection of entities. - * @param Collection $entities - * @throws \Throwable + * + * @throws Throwable */ - public function buildJointPermissionsForEntities(Collection $entities) + public function buildJointPermissionsForEntities(array $entities) { - $roles = $this->role->newQuery()->get(); - $this->deleteManyJointPermissionsForEntities($entities->all()); + $roles = Role::query()->get()->values()->all(); + $this->deleteManyJointPermissionsForEntities($entities); $this->createManyJointPermissions($entities, $roles); } /** * Build the entity jointPermissions for a particular role. - * @param Role $role */ public function buildJointPermissionForRole(Role $role) { @@ -288,7 +255,7 @@ class PermissionService }); // Chunk through all bookshelves - $this->entityProvider->bookshelf->newQuery()->select(['id', 'restricted', 'owned_by']) + Bookshelf::query()->select(['id', 'restricted', 'owned_by']) ->chunk(50, function ($shelves) use ($roles) { $this->buildJointPermissionsForShelves($shelves, $roles); }); @@ -296,7 +263,6 @@ class PermissionService /** * Delete the entity jointPermissions attached to a particular role. - * @param Role $role */ public function deleteJointPermissionsForRole(Role $role) { @@ -305,6 +271,7 @@ class PermissionService /** * Delete all of the entity jointPermissions for a list of entities. + * * @param Role[] $roles */ protected function deleteManyJointPermissionsForRoles($roles) @@ -312,13 +279,15 @@ class PermissionService $roleIds = array_map(function ($role) { return $role->id; }, $roles); - $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete(); + JointPermission::query()->whereIn('role_id', $roleIds)->delete(); } /** * Delete the entity jointPermissions for a particular entity. + * * @param Entity $entity - * @throws \Throwable + * + * @throws Throwable */ public function deleteJointPermissionsForEntity(Entity $entity) { @@ -327,17 +296,18 @@ class PermissionService /** * Delete all of the entity jointPermissions for a list of entities. - * @param \BookStack\Entities\Models\Entity[] $entities - * @throws \Throwable + * + * @param Entity[] $entities + * + * @throws Throwable */ - protected function deleteManyJointPermissionsForEntities($entities) + protected function deleteManyJointPermissionsForEntities(array $entities) { if (count($entities) === 0) { return; } $this->db->transaction(function () use ($entities) { - foreach (array_chunk($entities, 1000) as $entityChunk) { $query = $this->db->table('joint_permissions'); foreach ($entityChunk as $entity) { @@ -352,19 +322,21 @@ class PermissionService } /** - * Create & Save entity jointPermissions for many entities and jointPermissions. - * @param Collection $entities - * @param array $roles - * @throws \Throwable + * Create & Save entity jointPermissions for many entities and roles. + * + * @param Entity[] $entities + * @param Role[] $roles + * + * @throws Throwable */ - protected function createManyJointPermissions($entities, $roles) + protected function createManyJointPermissions(array $entities, array $roles) { $this->readyEntityCache($entities); $jointPermissions = []; // Fetch Entity Permissions and create a mapping of entity restricted statuses $entityRestrictedMap = []; - $permissionFetch = $this->entityPermission->newQuery(); + $permissionFetch = EntityPermission::query(); foreach ($entities as $entity) { $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted')); $permissionFetch->orWhere(function ($query) use ($entity) { @@ -405,35 +377,27 @@ class PermissionService }); } - /** * Get the actions related to an entity. - * @param \BookStack\Entities\Models\Entity $entity - * @return array */ - protected function getActions(Entity $entity) + protected function getActions(Entity $entity): array { $baseActions = ['view', 'update', 'delete']; - if ($entity->isA('chapter') || $entity->isA('book')) { + if ($entity instanceof Chapter || $entity instanceof Book) { $baseActions[] = 'page-create'; } - if ($entity->isA('book')) { + if ($entity instanceof Book) { $baseActions[] = 'chapter-create'; } + return $baseActions; } /** * Create entity permission data for an entity and role * for a particular action. - * @param Entity $entity - * @param Role $role - * @param string $action - * @param array $permissionMap - * @param array $rolePermissionMap - * @return array */ - protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap) + protected function createJointPermissionData(Entity $entity, Role $role, string $action, array $permissionMap, array $rolePermissionMap): array { $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action; $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']); @@ -447,10 +411,11 @@ class PermissionService if ($entity->restricted) { $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction); + return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess); } - if ($entity->isA('book') || $entity->isA('bookshelf')) { + if ($entity instanceof Book || $entity instanceof Bookshelf) { return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn); } @@ -460,7 +425,7 @@ class PermissionService $hasPermissiveAccessToParents = !$book->restricted; // For pages with a chapter, Check if explicit permissions are set on the Chapter - if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') { + if ($entity instanceof Page && intval($entity->chapter_id) !== 0) { $chapter = $this->getChapter($entity->chapter_id); $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted; if ($chapter->restricted) { @@ -479,29 +444,19 @@ class PermissionService /** * Check for an active restriction in an entity map. - * @param $entityMap - * @param Entity $entity - * @param Role $role - * @param $action - * @return bool */ - protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action) + protected function mapHasActiveRestriction(array $entityMap, Entity $entity, Role $role, string $action): bool { $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action; - return isset($entityMap[$key]) ? $entityMap[$key] : false; + + return $entityMap[$key] ?? false; } /** * Create an array of data with the information of an entity jointPermissions. * Used to build data for bulk insertion. - * @param \BookStack\Entities\Models\Entity $entity - * @param Role $role - * @param $action - * @param $permissionAll - * @param $permissionOwn - * @return array */ - protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn) + protected function createJointPermissionDataArray(Entity $entity, Role $role, string $action, bool $permissionAll, bool $permissionOwn): array { return [ 'role_id' => $role->getRawAttribute('id'), @@ -510,12 +465,13 @@ class PermissionService 'action' => $action, 'has_permission' => $permissionAll, 'has_permission_own' => $permissionOwn, - 'owned_by' => $entity->getRawAttribute('owned_by') + 'owned_by' => $entity->getRawAttribute('owned_by'), ]; } /** * Checks if an entity has a restriction set upon it. + * * @param HasCreatorAndUpdater|HasOwner $ownable */ public function checkOwnableUserAccess(Model $ownable, string $permission): bool @@ -524,104 +480,76 @@ class PermissionService $baseQuery = $ownable->newQuery()->where('id', '=', $ownable->id); $action = end($explodedPermission); - $this->currentAction = $action; + $user = $this->currentUser(); $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment']; // Handle non entity specific jointPermissions if (in_array($explodedPermission[0], $nonJointPermissions)) { - $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all'); - $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own'); - $this->currentAction = 'view'; + $allPermission = $user && $user->can($permission . '-all'); + $ownPermission = $user && $user->can($permission . '-own'); $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by'; - $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->$ownerField; - return ($allPermission || ($isOwner && $ownPermission)); + $isOwner = $user && $user->id === $ownable->$ownerField; + + return $allPermission || ($isOwner && $ownPermission); } // Handle abnormal create jointPermissions if ($action === 'create') { - $this->currentAction = $permission; + $action = $permission; } - $q = $this->entityRestrictionQuery($baseQuery)->count() > 0; + $hasAccess = $this->entityRestrictionQuery($baseQuery, $action)->count() > 0; $this->clean(); - return $q; + + return $hasAccess; } /** * Checks if a user has the given permission for any items in the system. * Can be passed an entity instance to filter on a specific type. - * @param string $permission - * @param string $entityClass - * @return bool */ - public function checkUserHasPermissionOnAnything(string $permission, string $entityClass = null) + public function checkUserHasPermissionOnAnything(string $permission, ?string $entityClass = null): bool { $userRoleIds = $this->currentUser()->roles()->select('id')->pluck('id')->toArray(); $userId = $this->currentUser()->id; - $permissionQuery = $this->db->table('joint_permissions') + $permissionQuery = JointPermission::query() ->where('action', '=', $permission) ->whereIn('role_id', $userRoleIds) - ->where(function ($query) use ($userId) { - $query->where('has_permission', '=', 1) - ->orWhere(function ($query2) use ($userId) { - $query2->where('has_permission_own', '=', 1) - ->where('owned_by', '=', $userId); - }); + ->where(function (Builder $query) use ($userId) { + $this->addJointHasPermissionCheck($query, $userId); }); if (!is_null($entityClass)) { - $entityInstance = app()->make($entityClass); + $entityInstance = app($entityClass); $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass()); } $hasPermission = $permissionQuery->count() > 0; $this->clean(); - return $hasPermission; - } - /** - * Check if an entity has restrictions set on itself or its - * parent tree. - * @param \BookStack\Entities\Models\Entity $entity - * @param $action - * @return bool|mixed - */ - public function checkIfRestrictionsSet(Entity $entity, $action) - { - $this->currentAction = $action; - if ($entity->isA('page')) { - return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted; - } elseif ($entity->isA('chapter')) { - return $entity->restricted || $entity->book->restricted; - } elseif ($entity->isA('book')) { - return $entity->restricted; - } + return $hasPermission; } /** * The general query filter to remove all entities * that the current user does not have access to. - * @param $query - * @return mixed - */ - protected function entityRestrictionQuery($query) - { - $q = $query->where(function ($parentQuery) { - $parentQuery->whereHas('jointPermissions', function ($permissionQuery) { - $permissionQuery->whereIn('role_id', $this->getRoles()) - ->where('action', '=', $this->currentAction) - ->where(function ($query) { - $query->where('has_permission', '=', true) - ->orWhere(function ($query) { - $query->where('has_permission_own', '=', true) - ->where('owned_by', '=', $this->currentUser()->id); - }); + */ + protected function entityRestrictionQuery(Builder $query, string $action): Builder + { + $q = $query->where(function ($parentQuery) use ($action) { + $parentQuery->whereHas('jointPermissions', function ($permissionQuery) use ($action) { + $permissionQuery->whereIn('role_id', $this->getCurrentUserRoles()) + ->where('action', '=', $action) + ->where(function (Builder $query) { + $this->addJointHasPermissionCheck($query, $this->currentUser()->id); }); }); }); + $this->clean(); + return $q; } @@ -632,16 +560,13 @@ class PermissionService public function restrictEntityQuery(Builder $query, string $ability = 'view'): Builder { $this->clean(); + return $query->where(function (Builder $parentQuery) use ($ability) { $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) use ($ability) { - $permissionQuery->whereIn('role_id', $this->getRoles()) + $permissionQuery->whereIn('role_id', $this->getCurrentUserRoles()) ->where('action', '=', $ability) ->where(function (Builder $query) { - $query->where('has_permission', '=', true) - ->orWhere(function (Builder $query) { - $query->where('has_permission_own', '=', true) - ->where('owned_by', '=', $this->currentUser()->id); - }); + $this->addJointHasPermissionCheck($query, $this->currentUser()->id); }); }); }); @@ -651,7 +576,7 @@ class PermissionService * Extend the given page query to ensure draft items are not visible * unless created by the given user. */ - public function enforceDraftVisiblityOnQuery(Builder $query): Builder + public function enforceDraftVisibilityOnQuery(Builder $query): Builder { return $query->where(function (Builder $query) { $query->where('draft', '=', false) @@ -663,109 +588,120 @@ class PermissionService } /** - * Add restrictions for a generic entity - * @param string $entityType - * @param Builder|\BookStack\Entities\Models\Entity $query - * @param string $action - * @return Builder + * Add restrictions for a generic entity. */ - public function enforceEntityRestrictions($entityType, $query, $action = 'view') + public function enforceEntityRestrictions(Entity $entity, Builder $query, string $action = 'view'): Builder { - if (strtolower($entityType) === 'page') { + if ($entity instanceof Page) { // Prevent drafts being visible to others. - $query = $query->where(function ($query) { - $query->where('draft', '=', false) - ->orWhere(function ($query) { - $query->where('draft', '=', true) - ->where('owned_by', '=', $this->currentUser()->id); - }); - }); + $this->enforceDraftVisibilityOnQuery($query); } - $this->currentAction = $action; - return $this->entityRestrictionQuery($query); + return $this->entityRestrictionQuery($query, $action); } /** * Filter items that have entities set as a polymorphic relation. - * @param $query - * @param string $tableName - * @param string $entityIdColumn - * @param string $entityTypeColumn - * @param string $action - * @return QueryBuilder + * For simplicity, this will not return results attached to draft pages. + * Draft pages should never really have related items though. + * + * @param Builder|QueryBuilder $query */ - public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view') + public function filterRestrictedEntityRelations($query, string $tableName, string $entityIdColumn, string $entityTypeColumn, string $action = 'view') { - - $this->currentAction = $action; $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn]; - - $q = $query->where(function ($query) use ($tableDetails) { - $query->whereExists(function ($permissionQuery) use (&$tableDetails) { - $permissionQuery->select('id')->from('joint_permissions') - ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn']) - ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn']) - ->where('action', '=', $this->currentAction) - ->whereIn('role_id', $this->getRoles()) - ->where(function ($query) { - $query->where('has_permission', '=', true)->orWhere(function ($query) { - $query->where('has_permission_own', '=', true) - ->where('owned_by', '=', $this->currentUser()->id); - }); - }); - }); + $pageMorphClass = (new Page())->getMorphClass(); + + $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) { + /** @var Builder $permissionQuery */ + $permissionQuery->select(['role_id'])->from('joint_permissions') + ->whereColumn('joint_permissions.entity_id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn']) + ->whereColumn('joint_permissions.entity_type', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn']) + ->where('joint_permissions.action', '=', $action) + ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoles()) + ->where(function (QueryBuilder $query) { + $this->addJointHasPermissionCheck($query, $this->currentUser()->id); + }); + })->where(function ($query) use ($tableDetails, $pageMorphClass) { + /** @var Builder $query */ + $query->where($tableDetails['entityTypeColumn'], '!=', $pageMorphClass) + ->orWhereExists(function (QueryBuilder $query) use ($tableDetails, $pageMorphClass) { + $query->select('id')->from('pages') + ->whereColumn('pages.id', '=', $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn']) + ->where($tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'], '=', $pageMorphClass) + ->where('pages.draft', '=', false); + }); }); + $this->clean(); + return $q; } /** * Add conditions to a query to filter the selection to related entities - * where permissions are granted. - * @param $entityType - * @param $query - * @param $tableName - * @param $entityIdColumn - * @return mixed - */ - public function filterRelatedEntity($entityType, $query, $tableName, $entityIdColumn) - { - $this->currentAction = 'view'; - $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn]; - - $pageMorphClass = $this->entityProvider->get($entityType)->getMorphClass(); - - $q = $query->where(function ($query) use ($tableDetails, $pageMorphClass) { - $query->where(function ($query) use (&$tableDetails, $pageMorphClass) { - $query->whereExists(function ($permissionQuery) use (&$tableDetails, $pageMorphClass) { - $permissionQuery->select('id')->from('joint_permissions') - ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn']) - ->where('entity_type', '=', $pageMorphClass) - ->where('action', '=', $this->currentAction) - ->whereIn('role_id', $this->getRoles()) - ->where(function ($query) { - $query->where('has_permission', '=', true)->orWhere(function ($query) { - $query->where('has_permission_own', '=', true) - ->where('owned_by', '=', $this->currentUser()->id); - }); - }); + * where view permissions are granted. + */ + public function filterRelatedEntity(string $entityClass, Builder $query, string $tableName, string $entityIdColumn): Builder + { + $fullEntityIdColumn = $tableName . '.' . $entityIdColumn; + $instance = new $entityClass(); + $morphClass = $instance->getMorphClass(); + + $existsQuery = function ($permissionQuery) use ($fullEntityIdColumn, $morphClass) { + /** @var Builder $permissionQuery */ + $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions') + ->whereColumn('joint_permissions.entity_id', '=', $fullEntityIdColumn) + ->where('joint_permissions.entity_type', '=', $morphClass) + ->where('joint_permissions.action', '=', 'view') + ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoles()) + ->where(function (QueryBuilder $query) { + $this->addJointHasPermissionCheck($query, $this->currentUser()->id); }); - })->orWhere($tableDetails['entityIdColumn'], '=', 0); + }; + + $q = $query->where(function ($query) use ($existsQuery, $fullEntityIdColumn) { + $query->whereExists($existsQuery) + ->orWhere($fullEntityIdColumn, '=', 0); }); + if ($instance instanceof Page) { + // Prevent visibility of non-owned draft pages + $q->whereExists(function (QueryBuilder $query) use ($fullEntityIdColumn) { + $query->select('id')->from('pages') + ->whereColumn('pages.id', '=', $fullEntityIdColumn) + ->where(function (QueryBuilder $query) { + $query->where('pages.draft', '=', false) + ->orWhere('pages.owned_by', '=', $this->currentUser()->id); + }); + }); + } + $this->clean(); return $q; } /** - * Get the current user - * @return \BookStack\Auth\User + * Add the query for checking the given user id has permission + * within the join_permissions table. + * + * @param QueryBuilder|Builder $query + */ + protected function addJointHasPermissionCheck($query, int $userIdToCheck) + { + $query->where('joint_permissions.has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) { + $query->where('joint_permissions.has_permission_own', '=', true) + ->where('joint_permissions.owned_by', '=', $userIdToCheck); + }); + } + + /** + * Get the current user. */ - private function currentUser() + private function currentUser(): User { - if ($this->currentUserModel === false) { + if (is_null($this->currentUserModel)) { $this->currentUserModel = user(); } @@ -775,10 +711,9 @@ class PermissionService /** * Clean the cached user elements. */ - private function clean() + private function clean(): void { - $this->currentUserModel = false; - $this->userRoles = false; - $this->isAdminUser = null; + $this->currentUserModel = null; + $this->userRoles = null; } }