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
208 public function buildJointPermissionsForEntity(Entity $entity)
210 $entities = [$entity];
211 if ($entity->isA('book')) {
212 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
213 $this->buildJointPermissionsForBooks($books, $this->role->newQuery()->get(), true);
217 $entities[] = $entity->book;
219 if ($entity->isA('page') && $entity->chapter_id) {
220 $entities[] = $entity->chapter;
223 if ($entity->isA('chapter')) {
224 foreach ($entity->pages as $page) {
229 $this->deleteManyJointPermissionsForEntities($entities);
230 $this->buildJointPermissionsForEntities(collect($entities));
234 * Rebuild the entity jointPermissions for a collection of entities.
235 * @param Collection $entities
237 public function buildJointPermissionsForEntities(Collection $entities)
239 $roles = $this->role->newQuery()->get();
240 $this->deleteManyJointPermissionsForEntities($entities->all());
241 $this->createManyJointPermissions($entities, $roles);
245 * Build the entity jointPermissions for a particular role.
248 public function buildJointPermissionForRole(Role $role)
251 $this->deleteManyJointPermissionsForRoles($roles);
253 // Chunk through all books
254 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
255 $this->buildJointPermissionsForBooks($books, $roles);
260 * Delete the entity jointPermissions attached to a particular role.
263 public function deleteJointPermissionsForRole(Role $role)
265 $this->deleteManyJointPermissionsForRoles([$role]);
269 * Delete all of the entity jointPermissions for a list of entities.
270 * @param Role[] $roles
272 protected function deleteManyJointPermissionsForRoles($roles)
274 $roleIds = array_map(function ($role) {
277 $this->jointPermission->newQuery()->whereIn('role_id', $roleIds)->delete();
281 * Delete the entity jointPermissions for a particular entity.
282 * @param Entity $entity
285 public function deleteJointPermissionsForEntity(Entity $entity)
287 $this->deleteManyJointPermissionsForEntities([$entity]);
291 * Delete all of the entity jointPermissions for a list of entities.
292 * @param Entity[] $entities
295 protected function deleteManyJointPermissionsForEntities($entities)
297 if (count($entities) === 0) {
301 $this->db->transaction(function () use ($entities) {
303 foreach (array_chunk($entities, 1000) as $entityChunk) {
304 $query = $this->db->table('joint_permissions');
305 foreach ($entityChunk as $entity) {
306 $query->orWhere(function (QueryBuilder $query) use ($entity) {
307 $query->where('entity_id', '=', $entity->id)
308 ->where('entity_type', '=', $entity->getMorphClass());
317 * Create & Save entity jointPermissions for many entities and jointPermissions.
318 * @param Collection $entities
319 * @param array $roles
322 protected function createManyJointPermissions($entities, $roles)
324 $this->readyEntityCache($entities);
325 $jointPermissions = [];
327 // Fetch Entity Permissions and create a mapping of entity restricted statuses
328 $entityRestrictedMap = [];
329 $permissionFetch = $this->entityPermission->newQuery();
330 foreach ($entities as $entity) {
331 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
332 $permissionFetch->orWhere(function ($query) use ($entity) {
333 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
336 $permissions = $permissionFetch->get();
338 // Create a mapping of explicit entity permissions
340 foreach ($permissions as $permission) {
341 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
342 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
343 $permissionMap[$key] = $isRestricted;
346 // Create a mapping of role permissions
347 $rolePermissionMap = [];
348 foreach ($roles as $role) {
349 foreach ($role->permissions as $permission) {
350 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
354 // Create Joint Permission Data
355 foreach ($entities as $entity) {
356 foreach ($roles as $role) {
357 foreach ($this->getActions($entity) as $action) {
358 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
363 $this->db->transaction(function () use ($jointPermissions) {
364 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
365 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
372 * Get the actions related to an entity.
373 * @param Entity $entity
376 protected function getActions(Entity $entity)
378 $baseActions = ['view', 'update', 'delete'];
379 if ($entity->isA('chapter') || $entity->isA('book')) {
380 $baseActions[] = 'page-create';
382 if ($entity->isA('book')) {
383 $baseActions[] = 'chapter-create';
389 * Create entity permission data for an entity and role
390 * for a particular action.
391 * @param Entity $entity
393 * @param string $action
394 * @param array $permissionMap
395 * @param array $rolePermissionMap
398 protected function createJointPermissionData(Entity $entity, Role $role, $action, $permissionMap, $rolePermissionMap)
400 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
401 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
402 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
403 $explodedAction = explode('-', $action);
404 $restrictionAction = end($explodedAction);
406 if ($role->system_name === 'admin') {
407 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
410 if ($entity->restricted) {
411 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
412 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
415 if ($entity->isA('book')) {
416 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
419 // For chapters and pages, Check if explicit permissions are set on the Book.
420 $book = $this->getBook($entity->book_id);
421 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
422 $hasPermissiveAccessToParents = !$book->restricted;
424 // For pages with a chapter, Check if explicit permissions are set on the Chapter
425 if ($entity->isA('page') && $entity->chapter_id !== 0 && $entity->chapter_id !== '0') {
426 $chapter = $this->getChapter($entity->chapter_id);
427 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
428 if ($chapter->restricted) {
429 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
433 return $this->createJointPermissionDataArray(
437 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
438 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
443 * Check for an active restriction in an entity map.
445 * @param Entity $entity
450 protected function mapHasActiveRestriction($entityMap, Entity $entity, Role $role, $action)
452 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
453 return isset($entityMap[$key]) ? $entityMap[$key] : false;
457 * Create an array of data with the information of an entity jointPermissions.
458 * Used to build data for bulk insertion.
459 * @param Entity $entity
462 * @param $permissionAll
463 * @param $permissionOwn
466 protected function createJointPermissionDataArray(Entity $entity, Role $role, $action, $permissionAll, $permissionOwn)
469 'role_id' => $role->getRawAttribute('id'),
470 'entity_id' => $entity->getRawAttribute('id'),
471 'entity_type' => $entity->getMorphClass(),
473 'has_permission' => $permissionAll,
474 'has_permission_own' => $permissionOwn,
475 'created_by' => $entity->getRawAttribute('created_by')
480 * Checks if an entity has a restriction set upon it.
481 * @param Ownable $ownable
485 public function checkOwnableUserAccess(Ownable $ownable, $permission)
487 if ($this->isAdmin()) {
492 $explodedPermission = explode('-', $permission);
494 $baseQuery = $ownable->where('id', '=', $ownable->id);
495 $action = end($explodedPermission);
496 $this->currentAction = $action;
498 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
500 // Handle non entity specific jointPermissions
501 if (in_array($explodedPermission[0], $nonJointPermissions)) {
502 $allPermission = $this->currentUser() && $this->currentUser()->can($permission . '-all');
503 $ownPermission = $this->currentUser() && $this->currentUser()->can($permission . '-own');
504 $this->currentAction = 'view';
505 $isOwner = $this->currentUser() && $this->currentUser()->id === $ownable->created_by;
506 return ($allPermission || ($isOwner && $ownPermission));
509 // Handle abnormal create jointPermissions
510 if ($action === 'create') {
511 $this->currentAction = $permission;
514 $q = $this->entityRestrictionQuery($baseQuery)->count() > 0;
520 * Check if an entity has restrictions set on itself or its
522 * @param Entity $entity
526 public function checkIfRestrictionsSet(Entity $entity, $action)
528 $this->currentAction = $action;
529 if ($entity->isA('page')) {
530 return $entity->restricted || ($entity->chapter && $entity->chapter->restricted) || $entity->book->restricted;
531 } elseif ($entity->isA('chapter')) {
532 return $entity->restricted || $entity->book->restricted;
533 } elseif ($entity->isA('book')) {
534 return $entity->restricted;
539 * The general query filter to remove all entities
540 * that the current user does not have access to.
544 protected function entityRestrictionQuery($query)
546 $q = $query->where(function ($parentQuery) {
547 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) {
548 $permissionQuery->whereIn('role_id', $this->getRoles())
549 ->where('action', '=', $this->currentAction)
550 ->where(function ($query) {
551 $query->where('has_permission', '=', true)
552 ->orWhere(function ($query) {
553 $query->where('has_permission_own', '=', true)
554 ->where('created_by', '=', $this->currentUser()->id);
564 * Get the children of a book in an efficient single query, Filtered by the permission system.
565 * @param integer $book_id
566 * @param bool $filterDrafts
567 * @param bool $fetchPageContent
568 * @return QueryBuilder
570 public function bookChildrenQuery($book_id, $filterDrafts = false, $fetchPageContent = false)
572 $pageSelect = $this->db->table('pages')->selectRaw($this->page->entityRawQuery($fetchPageContent))->where('book_id', '=', $book_id)->where(function ($query) use ($filterDrafts) {
573 $query->where('draft', '=', 0);
574 if (!$filterDrafts) {
575 $query->orWhere(function ($query) {
576 $query->where('draft', '=', 1)->where('created_by', '=', $this->currentUser()->id);
580 $chapterSelect = $this->db->table('chapters')->selectRaw($this->chapter->entityRawQuery())->where('book_id', '=', $book_id);
581 $query = $this->db->query()->select('*')->from($this->db->raw("({$pageSelect->toSql()} UNION {$chapterSelect->toSql()}) AS U"))
582 ->mergeBindings($pageSelect)->mergeBindings($chapterSelect);
584 if (!$this->isAdmin()) {
585 $whereQuery = $this->db->table('joint_permissions as jp')->selectRaw('COUNT(*)')
586 ->whereRaw('jp.entity_id=U.id')->whereRaw('jp.entity_type=U.entity_type')
587 ->where('jp.action', '=', 'view')->whereIn('jp.role_id', $this->getRoles())
588 ->where(function ($query) {
589 $query->where('jp.has_permission', '=', 1)->orWhere(function ($query) {
590 $query->where('jp.has_permission_own', '=', 1)->where('jp.created_by', '=', $this->currentUser()->id);
593 $query->whereRaw("({$whereQuery->toSql()}) > 0")->mergeBindings($whereQuery);
596 $query->orderBy('draft', 'desc')->orderBy('priority', 'asc');
602 * Add restrictions for a generic entity
603 * @param string $entityType
604 * @param Builder|Entity $query
605 * @param string $action
608 public function enforceEntityRestrictions($entityType, $query, $action = 'view')
610 if (strtolower($entityType) === 'page') {
611 // Prevent drafts being visible to others.
612 $query = $query->where(function ($query) {
613 $query->where('draft', '=', false);
614 if ($this->currentUser()) {
615 $query->orWhere(function ($query) {
616 $query->where('draft', '=', true)->where('created_by', '=', $this->currentUser()->id);
622 if ($this->isAdmin()) {
627 $this->currentAction = $action;
628 return $this->entityRestrictionQuery($query);
632 * Filter items that have entities set as a polymorphic relation.
634 * @param string $tableName
635 * @param string $entityIdColumn
636 * @param string $entityTypeColumn
637 * @param string $action
640 public function filterRestrictedEntityRelations($query, $tableName, $entityIdColumn, $entityTypeColumn, $action = 'view')
642 if ($this->isAdmin()) {
647 $this->currentAction = $action;
648 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
650 $q = $query->where(function ($query) use ($tableDetails) {
651 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
652 $permissionQuery->select('id')->from('joint_permissions')
653 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
654 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
655 ->where('action', '=', $this->currentAction)
656 ->whereIn('role_id', $this->getRoles())
657 ->where(function ($query) {
658 $query->where('has_permission', '=', true)->orWhere(function ($query) {
659 $query->where('has_permission_own', '=', true)
660 ->where('created_by', '=', $this->currentUser()->id);
670 * Filters pages that are a direct relation to another item.
673 * @param $entityIdColumn
676 public function filterRelatedPages($query, $tableName, $entityIdColumn)
678 if ($this->isAdmin()) {
683 $this->currentAction = 'view';
684 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
686 $q = $query->where(function ($query) use ($tableDetails) {
687 $query->where(function ($query) use (&$tableDetails) {
688 $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
689 $permissionQuery->select('id')->from('joint_permissions')
690 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
691 ->where('entity_type', '=', 'Bookstack\\Page')
692 ->where('action', '=', $this->currentAction)
693 ->whereIn('role_id', $this->getRoles())
694 ->where(function ($query) {
695 $query->where('has_permission', '=', true)->orWhere(function ($query) {
696 $query->where('has_permission_own', '=', true)
697 ->where('created_by', '=', $this->currentUser()->id);
701 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
708 * Check if the current user is an admin.
711 private function isAdmin()
713 if ($this->isAdminUser === null) {
714 $this->isAdminUser = ($this->currentUser()->id !== null) ? $this->currentUser()->hasSystemRole('admin') : false;
717 return $this->isAdminUser;
721 * Get the current user
724 private function currentUser()
726 if ($this->currentUserModel === false) {
727 $this->currentUserModel = user();
730 return $this->currentUserModel;
734 * Clean the cached user elements.
736 private function clean()
738 $this->currentUserModel = false;
739 $this->userRoles = false;
740 $this->isAdminUser = null;