1 <?php namespace BookStack\Auth\Permissions;
3 use BookStack\Auth\Role;
4 use BookStack\Auth\User;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\BookChild;
7 use BookStack\Entities\Models\Bookshelf;
8 use BookStack\Entities\Models\Chapter;
9 use BookStack\Entities\Models\Entity;
10 use BookStack\Entities\Models\Page;
12 use BookStack\Traits\HasCreatorAndUpdater;
13 use BookStack\Traits\HasOwner;
14 use Illuminate\Database\Connection;
15 use Illuminate\Database\Eloquent\Builder;
16 use Illuminate\Database\Eloquent\Collection as EloquentCollection;
17 use Illuminate\Database\Query\Builder as QueryBuilder;
20 class PermissionService
25 protected $userRoles = null;
30 protected $currentUserModel = null;
40 protected $entityCache;
43 * PermissionService constructor.
45 public function __construct(Connection $db)
51 * Set the database connection
53 public function setConnection(Connection $connection)
55 $this->db = $connection;
59 * Prepare the local entity cache and ensure it's empty
60 * @param Entity[] $entities
62 protected function readyEntityCache(array $entities = [])
64 $this->entityCache = [];
66 foreach ($entities as $entity) {
67 $class = get_class($entity);
68 if (!isset($this->entityCache[$class])) {
69 $this->entityCache[$class] = collect();
71 $this->entityCache[$class]->put($entity->id, $entity);
76 * Get a book via ID, Checks local cache
78 protected function getBook(int $bookId): ?Book
80 if (isset($this->entityCache[Book::class]) && $this->entityCache[Book::class]->has($bookId)) {
81 return $this->entityCache[Book::class]->get($bookId);
84 return Book::query()->withTrashed()->find($bookId);
88 * Get a chapter via ID, Checks local cache
90 protected function getChapter(int $chapterId): ?Chapter
92 if (isset($this->entityCache[Chapter::class]) && $this->entityCache[Chapter::class]->has($chapterId)) {
93 return $this->entityCache[Chapter::class]->get($chapterId);
96 return Chapter::query()
102 * Get the roles for the current logged in user.
104 protected function getCurrentUserRoles(): array
106 if (!is_null($this->userRoles)) {
107 return $this->userRoles;
110 if (auth()->guest()) {
111 $this->userRoles = [Role::getSystemRole('public')->id];
113 $this->userRoles = $this->currentUser()->roles->pluck('id')->values()->all();
116 return $this->userRoles;
120 * Re-generate all entity permission from scratch.
122 public function buildJointPermissions()
124 JointPermission::query()->truncate();
125 $this->readyEntityCache();
127 // Get all roles (Should be the most limited dimension)
128 $roles = Role::query()->with('permissions')->get()->all();
130 // Chunk through all books
131 $this->bookFetchQuery()->chunk(5, function (EloquentCollection $books) use ($roles) {
132 $this->buildJointPermissionsForBooks($books, $roles);
135 // Chunk through all bookshelves
136 Bookshelf::query()->withTrashed()->select(['id', 'restricted', 'owned_by'])
137 ->chunk(50, function (EloquentCollection $shelves) use ($roles) {
138 $this->buildJointPermissionsForShelves($shelves, $roles);
143 * Get a query for fetching a book with it's children.
145 protected function bookFetchQuery(): Builder
147 return Book::query()->withTrashed()
148 ->select(['id', 'restricted', 'owned_by'])->with([
149 'chapters' => function ($query) {
150 $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id']);
152 'pages' => function ($query) {
153 $query->withTrashed()->select(['id', 'restricted', 'owned_by', 'book_id', 'chapter_id']);
159 * Build joint permissions for the given shelf and role combinations.
162 protected function buildJointPermissionsForShelves(EloquentCollection $shelves, array $roles, bool $deleteOld = false)
165 $this->deleteManyJointPermissionsForEntities($shelves->all());
167 $this->createManyJointPermissions($shelves->all(), $roles);
171 * Build joint permissions for the given book and role combinations.
174 protected function buildJointPermissionsForBooks(EloquentCollection $books, array $roles, bool $deleteOld = false)
176 $entities = clone $books;
178 /** @var Book $book */
179 foreach ($books->all() as $book) {
180 foreach ($book->getRelation('chapters') as $chapter) {
181 $entities->push($chapter);
183 foreach ($book->getRelation('pages') as $page) {
184 $entities->push($page);
189 $this->deleteManyJointPermissionsForEntities($entities->all());
191 $this->createManyJointPermissions($entities->all(), $roles);
195 * Rebuild the entity jointPermissions for a particular entity.
198 public function buildJointPermissionsForEntity(Entity $entity)
200 $entities = [$entity];
201 if ($entity instanceof Book) {
202 $books = $this->bookFetchQuery()->where('id', '=', $entity->id)->get();
203 $this->buildJointPermissionsForBooks($books, Role::query()->get()->all(), true);
207 /** @var BookChild $entity */
209 $entities[] = $entity->book;
212 if ($entity instanceof Page && $entity->chapter_id) {
213 $entities[] = $entity->chapter;
216 if ($entity instanceof Chapter) {
217 foreach ($entity->pages as $page) {
222 $this->buildJointPermissionsForEntities($entities);
226 * Rebuild the entity jointPermissions for a collection of entities.
229 public function buildJointPermissionsForEntities(array $entities)
231 $roles = Role::query()->get()->values()->all();
232 $this->deleteManyJointPermissionsForEntities($entities);
233 $this->createManyJointPermissions($entities, $roles);
237 * Build the entity jointPermissions for a particular role.
239 public function buildJointPermissionForRole(Role $role)
242 $this->deleteManyJointPermissionsForRoles($roles);
244 // Chunk through all books
245 $this->bookFetchQuery()->chunk(20, function ($books) use ($roles) {
246 $this->buildJointPermissionsForBooks($books, $roles);
249 // Chunk through all bookshelves
250 Bookshelf::query()->select(['id', 'restricted', 'owned_by'])
251 ->chunk(50, function ($shelves) use ($roles) {
252 $this->buildJointPermissionsForShelves($shelves, $roles);
257 * Delete the entity jointPermissions attached to a particular role.
259 public function deleteJointPermissionsForRole(Role $role)
261 $this->deleteManyJointPermissionsForRoles([$role]);
265 * Delete all of the entity jointPermissions for a list of entities.
266 * @param Role[] $roles
268 protected function deleteManyJointPermissionsForRoles($roles)
270 $roleIds = array_map(function ($role) {
273 JointPermission::query()->whereIn('role_id', $roleIds)->delete();
277 * Delete the entity jointPermissions for a particular entity.
278 * @param Entity $entity
281 public function deleteJointPermissionsForEntity(Entity $entity)
283 $this->deleteManyJointPermissionsForEntities([$entity]);
287 * Delete all of the entity jointPermissions for a list of entities.
288 * @param Entity[] $entities
291 protected function deleteManyJointPermissionsForEntities(array $entities)
293 if (count($entities) === 0) {
297 $this->db->transaction(function () use ($entities) {
299 foreach (array_chunk($entities, 1000) as $entityChunk) {
300 $query = $this->db->table('joint_permissions');
301 foreach ($entityChunk as $entity) {
302 $query->orWhere(function (QueryBuilder $query) use ($entity) {
303 $query->where('entity_id', '=', $entity->id)
304 ->where('entity_type', '=', $entity->getMorphClass());
313 * Create & Save entity jointPermissions for many entities and roles.
314 * @param Entity[] $entities
315 * @param Role[] $roles
318 protected function createManyJointPermissions(array $entities, array $roles)
320 $this->readyEntityCache($entities);
321 $jointPermissions = [];
323 // Fetch Entity Permissions and create a mapping of entity restricted statuses
324 $entityRestrictedMap = [];
325 $permissionFetch = EntityPermission::query();
326 foreach ($entities as $entity) {
327 $entityRestrictedMap[$entity->getMorphClass() . ':' . $entity->id] = boolval($entity->getRawAttribute('restricted'));
328 $permissionFetch->orWhere(function ($query) use ($entity) {
329 $query->where('restrictable_id', '=', $entity->id)->where('restrictable_type', '=', $entity->getMorphClass());
332 $permissions = $permissionFetch->get();
334 // Create a mapping of explicit entity permissions
336 foreach ($permissions as $permission) {
337 $key = $permission->restrictable_type . ':' . $permission->restrictable_id . ':' . $permission->role_id . ':' . $permission->action;
338 $isRestricted = $entityRestrictedMap[$permission->restrictable_type . ':' . $permission->restrictable_id];
339 $permissionMap[$key] = $isRestricted;
342 // Create a mapping of role permissions
343 $rolePermissionMap = [];
344 foreach ($roles as $role) {
345 foreach ($role->permissions as $permission) {
346 $rolePermissionMap[$role->getRawAttribute('id') . ':' . $permission->getRawAttribute('name')] = true;
350 // Create Joint Permission Data
351 foreach ($entities as $entity) {
352 foreach ($roles as $role) {
353 foreach ($this->getActions($entity) as $action) {
354 $jointPermissions[] = $this->createJointPermissionData($entity, $role, $action, $permissionMap, $rolePermissionMap);
359 $this->db->transaction(function () use ($jointPermissions) {
360 foreach (array_chunk($jointPermissions, 1000) as $jointPermissionChunk) {
361 $this->db->table('joint_permissions')->insert($jointPermissionChunk);
368 * Get the actions related to an entity.
370 protected function getActions(Entity $entity): array
372 $baseActions = ['view', 'update', 'delete'];
373 if ($entity instanceof Chapter || $entity instanceof Book) {
374 $baseActions[] = 'page-create';
376 if ($entity instanceof Book) {
377 $baseActions[] = 'chapter-create';
383 * Create entity permission data for an entity and role
384 * for a particular action.
386 protected function createJointPermissionData(Entity $entity, Role $role, string $action, array $permissionMap, array $rolePermissionMap): array
388 $permissionPrefix = (strpos($action, '-') === false ? ($entity->getType() . '-') : '') . $action;
389 $roleHasPermission = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-all']);
390 $roleHasPermissionOwn = isset($rolePermissionMap[$role->getRawAttribute('id') . ':' . $permissionPrefix . '-own']);
391 $explodedAction = explode('-', $action);
392 $restrictionAction = end($explodedAction);
394 if ($role->system_name === 'admin') {
395 return $this->createJointPermissionDataArray($entity, $role, $action, true, true);
398 if ($entity->restricted) {
399 $hasAccess = $this->mapHasActiveRestriction($permissionMap, $entity, $role, $restrictionAction);
400 return $this->createJointPermissionDataArray($entity, $role, $action, $hasAccess, $hasAccess);
403 if ($entity instanceof Book || $entity instanceof Bookshelf) {
404 return $this->createJointPermissionDataArray($entity, $role, $action, $roleHasPermission, $roleHasPermissionOwn);
407 // For chapters and pages, Check if explicit permissions are set on the Book.
408 $book = $this->getBook($entity->book_id);
409 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $book, $role, $restrictionAction);
410 $hasPermissiveAccessToParents = !$book->restricted;
412 // For pages with a chapter, Check if explicit permissions are set on the Chapter
413 if ($entity instanceof Page && intval($entity->chapter_id) !== 0) {
414 $chapter = $this->getChapter($entity->chapter_id);
415 $hasPermissiveAccessToParents = $hasPermissiveAccessToParents && !$chapter->restricted;
416 if ($chapter->restricted) {
417 $hasExplicitAccessToParents = $this->mapHasActiveRestriction($permissionMap, $chapter, $role, $restrictionAction);
421 return $this->createJointPermissionDataArray(
425 ($hasExplicitAccessToParents || ($roleHasPermission && $hasPermissiveAccessToParents)),
426 ($hasExplicitAccessToParents || ($roleHasPermissionOwn && $hasPermissiveAccessToParents))
431 * Check for an active restriction in an entity map.
433 protected function mapHasActiveRestriction(array $entityMap, Entity $entity, Role $role, string $action): bool
435 $key = $entity->getMorphClass() . ':' . $entity->getRawAttribute('id') . ':' . $role->getRawAttribute('id') . ':' . $action;
436 return $entityMap[$key] ?? false;
440 * Create an array of data with the information of an entity jointPermissions.
441 * Used to build data for bulk insertion.
443 protected function createJointPermissionDataArray(Entity $entity, Role $role, string $action, bool $permissionAll, bool $permissionOwn): array
446 'role_id' => $role->getRawAttribute('id'),
447 'entity_id' => $entity->getRawAttribute('id'),
448 'entity_type' => $entity->getMorphClass(),
450 'has_permission' => $permissionAll,
451 'has_permission_own' => $permissionOwn,
452 'owned_by' => $entity->getRawAttribute('owned_by'),
457 * Checks if an entity has a restriction set upon it.
458 * @param HasCreatorAndUpdater|HasOwner $ownable
460 public function checkOwnableUserAccess(Model $ownable, string $permission): bool
462 $explodedPermission = explode('-', $permission);
464 $baseQuery = $ownable->newQuery()->where('id', '=', $ownable->id);
465 $action = end($explodedPermission);
466 $user = $this->currentUser();
468 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
470 // Handle non entity specific jointPermissions
471 if (in_array($explodedPermission[0], $nonJointPermissions)) {
472 $allPermission = $user && $user->can($permission . '-all');
473 $ownPermission = $user && $user->can($permission . '-own');
474 $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
475 $isOwner = $user && $user->id === $ownable->$ownerField;
476 return ($allPermission || ($isOwner && $ownPermission));
479 // Handle abnormal create jointPermissions
480 if ($action === 'create') {
481 $action = $permission;
484 $hasAccess = $this->entityRestrictionQuery($baseQuery, $action)->count() > 0;
490 * Checks if a user has the given permission for any items in the system.
491 * Can be passed an entity instance to filter on a specific type.
493 public function checkUserHasPermissionOnAnything(string $permission, ?string $entityClass = null): bool
495 $userRoleIds = $this->currentUser()->roles()->select('id')->pluck('id')->toArray();
496 $userId = $this->currentUser()->id;
498 $permissionQuery = JointPermission::query()
499 ->where('action', '=', $permission)
500 ->whereIn('role_id', $userRoleIds)
501 ->where(function (Builder $query) use ($userId) {
502 $this->addJointHasPermissionCheck($query, $userId);
505 if (!is_null($entityClass)) {
506 $entityInstance = app($entityClass);
507 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
510 $hasPermission = $permissionQuery->count() > 0;
512 return $hasPermission;
516 * The general query filter to remove all entities
517 * that the current user does not have access to.
519 protected function entityRestrictionQuery(Builder $query, string $action): Builder
521 $q = $query->where(function ($parentQuery) use ($action) {
522 $parentQuery->whereHas('jointPermissions', function ($permissionQuery) use ($action) {
523 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoles())
524 ->where('action', '=', $action)
525 ->where(function (Builder $query) {
526 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
536 * Limited the given entity query so that the query will only
537 * return items that the user has permission for the given ability.
539 public function restrictEntityQuery(Builder $query, string $ability = 'view'): Builder
542 return $query->where(function (Builder $parentQuery) use ($ability) {
543 $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) use ($ability) {
544 $permissionQuery->whereIn('role_id', $this->getCurrentUserRoles())
545 ->where('action', '=', $ability)
546 ->where(function (Builder $query) {
547 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
554 * Extend the given page query to ensure draft items are not visible
555 * unless created by the given user.
557 public function enforceDraftVisibilityOnQuery(Builder $query): Builder
559 return $query->where(function (Builder $query) {
560 $query->where('draft', '=', false)
561 ->orWhere(function (Builder $query) {
562 $query->where('draft', '=', true)
563 ->where('owned_by', '=', $this->currentUser()->id);
569 * Add restrictions for a generic entity.
571 public function enforceEntityRestrictions(Entity $entity, Builder $query, string $action = 'view'): Builder
573 if ($entity instanceof Page) {
574 // Prevent drafts being visible to others.
575 $this->enforceDraftVisibilityOnQuery($query);
578 return $this->entityRestrictionQuery($query, $action);
582 * Filter items that have entities set as a polymorphic relation.
583 * @param Builder|\Illuminate\Database\Query\Builder $query
585 public function filterRestrictedEntityRelations($query, string $tableName, string $entityIdColumn, string $entityTypeColumn, string $action = 'view')
587 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
589 $q = $query->where(function ($query) use ($tableDetails, $action) {
590 $query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) {
591 $permissionQuery->select(['role_id'])->from('joint_permissions')
592 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
593 ->whereRaw('joint_permissions.entity_type=' . $tableDetails['tableName'] . '.' . $tableDetails['entityTypeColumn'])
594 ->where('action', '=', $action)
595 ->whereIn('role_id', $this->getCurrentUserRoles())
596 ->where(function (QueryBuilder $query) {
597 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
607 * Add conditions to a query to filter the selection to related entities
608 * where view permissions are granted.
610 public function filterRelatedEntity(string $entityClass, Builder $query, string $tableName, string $entityIdColumn): Builder
612 $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn];
613 $morphClass = app($entityClass)->getMorphClass();
615 $q = $query->where(function ($query) use ($tableDetails, $morphClass) {
616 $query->where(function ($query) use (&$tableDetails, $morphClass) {
617 $query->whereExists(function ($permissionQuery) use (&$tableDetails, $morphClass) {
618 $permissionQuery->select('id')->from('joint_permissions')
619 ->whereRaw('joint_permissions.entity_id=' . $tableDetails['tableName'] . '.' . $tableDetails['entityIdColumn'])
620 ->where('entity_type', '=', $morphClass)
621 ->where('action', '=', 'view')
622 ->whereIn('role_id', $this->getCurrentUserRoles())
623 ->where(function (QueryBuilder $query) {
624 $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
627 })->orWhere($tableDetails['entityIdColumn'], '=', 0);
635 * Add the query for checking the given user id has permission
636 * within the join_permissions table.
637 * @param QueryBuilder|Builder $query
639 protected function addJointHasPermissionCheck($query, int $userIdToCheck)
641 $query->where('has_permission', '=', true)->orWhere(function ($query) use ($userIdToCheck) {
642 $query->where('has_permission_own', '=', true)
643 ->where('owned_by', '=', $userIdToCheck);
648 * Get the current user
650 private function currentUser(): User
652 if (is_null($this->currentUserModel)) {
653 $this->currentUserModel = user();
656 return $this->currentUserModel;
660 * Clean the cached user elements.
662 private function clean(): void
664 $this->currentUserModel = null;
665 $this->userRoles = null;