1 <?php namespace BookStack\Services;
6 use BookStack\EntityPermission;
7 use BookStack\JointPermission;
12 use Illuminate\Database\Connection;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Query\Builder as QueryBuilder;
15 use Illuminate\Support\Collection;
17 class PermissionService
20 protected $currentAction;
21 protected $isAdminUser;
22 protected $userRoles = false;
23 protected $currentUserModel = false;
31 protected $jointPermission;
33 protected $entityPermission;
35 protected $entityCache;
38 * PermissionService constructor.
39 * @param JointPermission $jointPermission
40 * @param EntityPermission $entityPermission
41 * @param Connection $db
43 * @param Chapter $chapter
47 public function __construct(JointPermission $jointPermission, EntityPermission $entityPermission, Connection $db, Book $book, Chapter $chapter, Page $page, Role $role)
50 $this->jointPermission = $jointPermission;
51 $this->entityPermission = $entityPermission;
54 $this->chapter = $chapter;
56 // TODO - Update so admin still goes through filters
60 * Set the database connection
61 * @param Connection $connection
63 public function setConnection(Connection $connection)
65 $this->db = $connection;
69 * Prepare the local entity cache and ensure it's empty
70 * @param Entity[] $entities
72 protected function readyEntityCache($entities = [])
74 $this->entityCache = [];
76 foreach ($entities as $entity) {
77 $type = $entity->getType();
78 if (!isset($this->entityCache[$type])) {
79 $this->entityCache[$type] = collect();
81 $this->entityCache[$type]->put($entity->id, $entity);
86 * Get a book via ID, Checks local cache
90 protected function getBook($bookId)
92 if (isset($this->entityCache['book']) && $this->entityCache['book']->has($bookId)) {
93 return $this->entityCache['book']->get($bookId);
96 $book = $this->book->find($bookId);
105 * Get a chapter via ID, Checks local cache
109 protected function getChapter($chapterId)
111 if (isset($this->entityCache['chapter']) && $this->entityCache['chapter']->has($chapterId)) {
112 return $this->entityCache['chapter']->get($chapterId);
115 $chapter = $this->chapter->find($chapterId);
116 if ($chapter === null) {
124 * Get the roles for the current user;
127 protected function getRoles()
129 if ($this->userRoles !== false) {
130 return $this->userRoles;
135 if (auth()->guest()) {
136 $roles[] = $this->role->getSystemRole('public')->id;
141 foreach ($this->currentUser()->roles as $role) {
142 $roles[] = $role->id;
148 * Re-generate all entity permission from scratch.
150 public function buildJointPermissions()
152 $this->jointPermission->truncate();
153 $this->readyEntityCache();
155 // Get all roles (Should be the most limited dimension)
156 $roles = $this->role->with('permissions')->get()->all();
158 // Chunk through all books
159 $this->bookFetchQuery()->chunk(5, function ($books) use ($roles) {
160 $this->buildJointPermissionsForBooks($books, $roles);
165 * Get a query for fetching a book with it's children.
166 * @return QueryBuilder
168 protected function bookFetchQuery()
170 return $this->book->newQuery()->select(['id', 'restricted', 'created_by'])->with(['chapters' => function ($query) {
171 $query->select(['id', 'restricted', 'created_by', 'book_id']);
172 }, 'pages' => function ($query) {
173 $query->select(['id', 'restricted', 'created_by', 'book_id', 'chapter_id']);
178 * Build joint permissions for an array of books
179 * @param Collection $books
180 * @param array $roles
181 * @param bool $deleteOld
184 protected function buildJointPermissionsForBooks($books, $roles, $deleteOld = false)
186 $entities = clone $books;
188 /** @var Book $book */
189 foreach ($books->all() as $book) {
190 foreach ($book->getRelation('chapters') as $chapter) {
191 $entities->push($chapter);
193 foreach ($book->getRelation('pages') as $page) {
194 $entities->push($page);
199 $this->deleteManyJointPermissionsForEntities($entities->all());
201 $this->createManyJointPermissions($entities, $roles);
205 * Rebuild the entity jointPermissions for a particular entity.
206 * @param Entity $entity
209 public function buildJointPermissionsForEntity(Entity $entity)
211 $entities = [$entity];
212 if ($entity->isA('book')) {
213 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
214 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
219 $entities[] = $entity->book;
222 if ($entity->isA('page') && $entity->chapter_id) {
223 $entities[] = $entity->chapter;
226 if ($entity->isA('chapter')) {
227 foreach ($entity->pages as $page) {
232 $this->buildJointPermissionsForEntities(collect($entities));
236 * Rebuild the entity jointPermissions for a collection of entities.
237 * @param Collection $entities
240 public function buildJointPermissionsForEntities(Collection $entities)
242 $roles = $this->role->newQuery()->get();
243 $this->deleteManyJointPermissionsForEntities($entities->all());
244 $this->createManyJointPermissions($entities, $roles);
248 * Build the entity jointPermissions for a particular role.
251 public function buildJointPermissionForRole(Role $role)
254 $this->deleteManyJointPermissionsForRoles($roles);
256 // Chunk through all books
257 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
258 $this->buildJointPermissionsForBooks($books, $roles);
263 * Delete the entity jointPermissions attached to a particular role.
266 public function deleteJointPermissionsForRole(Role $role)
268 $this->deleteManyJointPermissionsForRoles([$role]);
272 * Delete all of the entity jointPermissions for a list of entities.
273 * @param Role[] $roles
275 protected function deleteManyJointPermissionsForRoles($roles)
277 $roleIds = array_map(function ($role) {
280 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
284 * Delete the entity jointPermissions for a particular entity.
285 * @param Entity $entity
288 public function deleteJointPermissionsForEntity(Entity $entity)
290 $this->deleteManyJointPermissionsForEntities([$entity]);
294 * Delete all of the entity jointPermissions for a list of entities.
295 * @param Entity[] $entities
298 protected function deleteManyJointPermissionsForEntities($entities)
300 if (count($entities) === 0) {
304 $this->db->transaction(function () use ($entities) {
306 foreach (array_chunk($entities, 1000) as $entityChunk) {
307 $query = $this->db->table('joint_permissions');
308 foreach ($entityChunk as $entity) {
309 $query->orWhere(function (QueryBuilder $query) use ($entity) {
310 $query->where('entity_id', '=', $entity->id)
311 ->where('entity_type', '=', $entity->getMorphClass());
320 * Create & Save entity jointPermissions for many entities and jointPermissions.
321 * @param Collection $entities
322 * @param array $roles
325 protected function createManyJointPermissions($entities, $roles)
327 $this->readyEntityCache($entities);
328 $jointPermissions = [];
330 // Fetch Entity Permissions and create a mapping of entity restricted statuses
331 $entityRestrictedMap = [];
332 $permissionFetch = $this->entityPermission->newQuery();
333 foreach ($entities as $entity) {
334 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
335 $permissionFetch->orWhere(function ($query) use ($entity) {
336 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
339 $permissions = $permissionFetch->get();
341 // Create a mapping of explicit entity permissions
343 foreach ($permissions as $permission) {
344 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
345 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
346 $permissionMap[$key] = $isRestricted;
349 // Create a mapping of role permissions
350 $rolePermissionMap = [];
351 foreach ($roles as $role) {
352 foreach ($role->permissions as $permission) {
353 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
357 // Create Joint Permission Data
358 foreach ($entities as $entity) {
359 foreach ($roles as $role) {
360 foreach ($this->getActions($entity) as $action) {
361 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
366 $this->db->transaction(function () use ($jointPermissions) {
367 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
368 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
375 * Get the actions related to an entity.
376 * @param Entity $entity
379 protected function getActions(Entity $entity)
381 $baseActions = ['view', 'update', 'delete'];
382 if ($entity->isA('chapter') || $entity->isA('book')) {
383 $baseActions[] = 'page-create';
385 if ($entity->isA('book')) {
386 $baseActions[] = 'chapter-create';
392 * Create entity permission data for an entity and role
393 * for a particular action.
394 * @param Entity $entity
396 * @param string $action
397 * @param array $permissionMap
398 * @param array $rolePermissionMap
401 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
403 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
404 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
405 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
406 $explodedAction = explode('-', $action);
407 $restrictionAction = end($explodedAction);
409 if ($role->system_name === 'admin') {
410 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
413 if ($entity->restricted) {
414 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
415 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
418 if ($entity->isA('book') || $entity->isA('bookshelf')) {
419 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
422 // For chapters and pages, Check if explicit permissions are set on the Book.
423 $book = $this->getBook($entity->book_id);
424 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
425 $hasPermissiveAccessToParents = !$book->restricted;
427 // For pages with a chapter, Check if explicit permissions are set on the Chapter
428 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
429 $chapter = $this->getChapter($entity->chapter_id);
430 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
431 if ($chapter->restricted) {
432 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
436 return $this->createJointPermissionDataArray(
440 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
441 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
446 * Check for an active restriction in an entity map.
448 * @param Entity $entity
453 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
455 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
456 return isset($entityMap[$key]) ? $entityMap[$key] : false;
460 * Create an array of data with the information of an entity jointPermissions.
461 * Used to build data for bulk insertion.
462 * @param Entity $entity
465 * @param $permissionAll
466 * @param $permissionOwn
469 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
472 'role_id' => $role->getRawAttribute('id'),
473 'entity_id' => $entity->getRawAttribute('id'),
474 'entity_type' => $entity->getMorphClass(),
476 'has_permission' => $permissionAll,
477 'has_permission_own' => $permissionOwn,
478 'created_by' => $entity->getRawAttribute('created_by')
483 * Checks if an entity has a restriction set upon it.
484 * @param Ownable $ownable
488 public function checkOwnableUserAccess(Ownable $ownable, $permission)
490 if ($this->isAdmin()) {
495 $explodedPermission = explode('-', $permission);
497 $baseQuery = $ownable->where('id', '=', $ownable->id);
498 $action = end($explodedPermission);
499 $this->currentAction = $action;
501 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
503 // Handle non entity specific jointPermissions
504 if (in_array($explodedPermission[0], $nonJointPermissions)) {
505 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
506 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
507 $this->currentAction = 'view';
508 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
509 return ($allPermission || ($isOwner && $ownPermission));
512 // Handle abnormal create jointPermissions
513 if ($action === 'create') {
514 $this->currentAction = $permission;
517 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
523 * Check if an entity has restrictions set on itself or its
525 * @param Entity $entity
529 public function checkIfRestrictionsSet(Entity $entity, $action)
531 $this->currentAction = $action;
532 if ($entity->isA('page')) {
533 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
534 } elseif ($entity->isA('chapter')) {
535 return $entity->restricted || $entity->book->restricted;
536 } elseif ($entity->isA('book')) {
537 return $entity->restricted;
542 * The general query filter to remove all entities
543 * that the current user does not have access to.
547 protected function entityRestrictionQuery($query)
549 $q = $query->where(function ($parentQuery) {
550 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
551 $permissionQuery->whereIn('role_id', $this->getRoles())
552 ->where('action', '=', $this->currentAction)
553 ->where(function ($query) {
554 $query->where('has_permission', '=', true)
555 ->orWhere(function ($query) {
556 $query->where('has_permission_own', '=', true)
557 ->where('created_by', '=', $this->currentUser()->id);
567 * Get the children of a book in an efficient single query, Filtered by the permission system.
568 * @param integer $book_id
569 * @param bool $filterDrafts
570 * @param bool $fetchPageContent
571 * @return QueryBuilder
573 public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false)
575 $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function ($query) use ($filterDrafts) {
576 $query->where('draft', '=', 0);
577 if (!$filterDrafts) {
578 $query->orWhere(function ($query) {
579 $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
583 $chapterSelect = $this->db->table('chapters')->selectRaw($this->chapter->entityRawQuery())->where('book_id', '=', $book_id);
584 $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
585 ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
587 if (!$this->isAdmin()) {
588 $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
589 ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
590 ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
591 ->where(function ($query) {
592 $query->where('jp.has_permission', '=', 1)->orWhere(function ($query) {
593 $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
596 $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
599 $query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
605 * Add restrictions for a generic entity
606 * @param string $entityType
607 * @param Builder|Entity $query
608 * @param string $action
611 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
613 if (strtolower($entityType) === 'page') {
614 // Prevent drafts being visible to others.
615 $query = $query->where(function ($query) {
616 $query->where('draft', '=', false);
617 if ($this->currentUser()) {
618 $query->orWhere(function ($query) {
619 $query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
625 if ($this->isAdmin()) {
630 $this->currentAction = $action;
631 return $this->entityRestrictionQuery($query);
635 * Filter items that have entities set as a polymorphic relation.
637 * @param string $tableName
638 * @param string $entityIdColumn
639 * @param string $entityTypeColumn
640 * @param string $action
643 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
645 if ($this->isAdmin()) {
650 $this->currentAction = $action;
651 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
653 $q = $query->where(function ($query) use ($tableDetails) {
654 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
655 $permissionQuery->select('id')->from('joint_permissions')
656 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
657 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
658 ->where('action', '=', $this->currentAction)
659 ->whereIn('role_id', $this->getRoles())
660 ->where(function ($query) {
661 $query->where('has_permission', '=', true)->orWhere(function ($query) {
662 $query->where('has_permission_own', '=', true)
663 ->where('created_by', '=', $this->currentUser()->id);
673 * Filters pages that are a direct relation to another item.
676 * @param $entityIdColumn
679 public function filterRelatedPages($query, $tableName, $entityIdColumn)
681 if ($this->isAdmin()) {
686 $this->currentAction = 'view';
687 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
689 $q = $query->where(function ($query) use ($tableDetails) {
690 $query->where(function ($query) use (&$tableDetails) {
691 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
692 $permissionQuery->select('id')->from('joint_permissions')
693 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
694 ->where('entity_type', '=', 'Bookstack\\Page')
695 ->where('action', '=', $this->currentAction)
696 ->whereIn('role_id', $this->getRoles())
697 ->where(function ($query) {
698 $query->where('has_permission', '=', true)->orWhere(function ($query) {
699 $query->where('has_permission_own', '=', true)
700 ->where('created_by', '=', $this->currentUser()->id);
704 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
711 * Check if the current user is an admin.
714 private function isAdmin()
716 if ($this->isAdminUser === null) {
717 $this->isAdminUser = ($this->currentUser()->id !== null) ? $this->currentUser()->hasSystemRole('admin') : false;
720 return $this->isAdminUser;
724 * Get the current user
727 private function currentUser()
729 if ($this->currentUserModel === false) {
730 $this->currentUserModel = user();
733 return $this->currentUserModel;
737 * Clean the cached user elements.
739 private function clean()
741 $this->currentUserModel = false;
742 $this->userRoles = false;
743 $this->isAdminUser = null;