]> BookStack Code Mirror - bookstack/blobdiff - app/Auth/Permissions/PermissionApplicator.php
Guest create page: name field autofocus
[bookstack] / app / Auth / Permissions / PermissionApplicator.php
index 40a7f61162336937192871ae23bb336cfbaca9e1..af372cb74002e264a950cfdaaa67cbde2e1f3e7c 100644 (file)
@@ -4,6 +4,7 @@ namespace BookStack\Auth\Permissions;
 
 use BookStack\Auth\Role;
 use BookStack\Auth\User;
+use BookStack\Entities\Models\Chapter;
 use BookStack\Entities\Models\Entity;
 use BookStack\Entities\Models\Page;
 use BookStack\Model;
@@ -11,37 +12,10 @@ use BookStack\Traits\HasCreatorAndUpdater;
 use BookStack\Traits\HasOwner;
 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Query\Builder as QueryBuilder;
+use InvalidArgumentException;
 
 class PermissionApplicator
 {
-    /**
-     * @var ?array<int>
-     */
-    protected $userRoles = null;
-
-    /**
-     * @var ?User
-     */
-    protected $currentUserModel = null;
-
-    /**
-     * Get the roles for the current logged in user.
-     */
-    protected function getCurrentUserRoles(): array
-    {
-        if (!is_null($this->userRoles)) {
-            return $this->userRoles;
-        }
-
-        if (auth()->guest()) {
-            $this->userRoles = [Role::getSystemRole('public')->id];
-        } else {
-            $this->userRoles = $this->currentUser()->roles->pluck('id')->values()->all();
-        }
-
-        return $this->userRoles;
-    }
-
     /**
      * Checks if an entity has a restriction set upon it.
      *
@@ -50,95 +24,117 @@ class PermissionApplicator
     public function checkOwnableUserAccess(Model $ownable, string $permission): bool
     {
         $explodedPermission = explode('-', $permission);
+        $action = $explodedPermission[1] ?? $explodedPermission[0];
+        $fullPermission = count($explodedPermission) > 1 ? $permission : $ownable->getMorphClass() . '-' . $permission;
 
-        $baseQuery = $ownable->newQuery()->where('id', '=', $ownable->id);
-        $action = end($explodedPermission);
         $user = $this->currentUser();
+        $userRoleIds = $this->getCurrentUserRoleIds();
 
+        $allRolePermission = $user->can($fullPermission . '-all');
+        $ownRolePermission = $user->can($fullPermission . '-own');
         $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
+        $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
+        $ownableFieldVal = $ownable->getAttribute($ownerField);
+
+        if (is_null($ownableFieldVal)) {
+            throw new InvalidArgumentException("{$ownerField} field used but has not been loaded");
+        }
+
+        $isOwner = $user->id === $ownableFieldVal;
+        $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
 
         // Handle non entity specific jointPermissions
         if (in_array($explodedPermission[0], $nonJointPermissions)) {
-            $allPermission = $user && $user->can($permission . '-all');
-            $ownPermission = $user && $user->can($permission . '-own');
-            $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
-            $isOwner = $user && $user->id === $ownable->$ownerField;
+            return $hasRolePermission;
+        }
+
+        $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $action);
+
+        return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
+    }
+
+    /**
+     * Check if there are permissions that are applicable for the given entity item, action and roles.
+     * Returns null when no entity permissions are in force.
+     */
+    protected function hasEntityPermission(Entity $entity, array $userRoleIds, string $action): ?bool
+    {
+        $this->ensureValidEntityAction($action);
 
-            return $allPermission || ($isOwner && $ownPermission);
+        $adminRoleId = Role::getSystemRole('admin')->id;
+        if (in_array($adminRoleId, $userRoleIds)) {
+            return true;
         }
 
-        // Handle abnormal create jointPermissions
-        if ($action === 'create') {
-            $action = $permission;
+        // The chain order here is very important due to the fact we walk up the chain
+        // in the loop below. Earlier items in the chain have higher priority.
+        $chain = [$entity];
+        if ($entity instanceof Page && $entity->chapter_id) {
+            $chain[] = $entity->chapter;
         }
 
-        // TODO - Use a non-query based check
-        $hasAccess = $this->entityRestrictionQuery($baseQuery, $action)->count() > 0;
-        $this->clean();
+        if ($entity instanceof Page || $entity instanceof Chapter) {
+            $chain[] = $entity->book;
+        }
+
+        foreach ($chain as $currentEntity) {
+            $allowedByRoleId = $currentEntity->permissions()
+                ->whereIn('role_id', [0, ...$userRoleIds])
+                ->pluck($action, 'role_id');
+
+            // Continue up the chain if no applicable entity permission overrides.
+            if ($allowedByRoleId->isEmpty()) {
+                continue;
+            }
+
+            // If we have user-role-specific permissions set, allow if any of those
+            // role permissions allow access.
+            $hasDefault = $allowedByRoleId->has(0);
+            if (!$hasDefault || $allowedByRoleId->count() > 1) {
+                return $allowedByRoleId->search(function (bool $allowed, int $roleId) {
+                        return $roleId !== 0 && $allowed;
+                }) !== false;
+            }
+
+            // Otherwise, return the default "Other roles" fallback value.
+            return $allowedByRoleId->get(0);
+        }
 
-        return $hasAccess;
+        return null;
     }
 
     /**
      * 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.
      */
-    public function checkUserHasPermissionOnAnything(string $permission, ?string $entityClass = null): bool
+    public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
     {
-        $userRoleIds = $this->currentUser()->roles()->select('id')->pluck('id')->toArray();
-        $userId = $this->currentUser()->id;
-
-        $permissionQuery = JointPermission::query()
-            ->where('action', '=', $permission)
-            ->whereIn('role_id', $userRoleIds)
-            ->where(function (Builder $query) use ($userId) {
-                $this->addJointHasPermissionCheck($query, $userId);
-            });
+        $this->ensureValidEntityAction($action);
 
-        if (!is_null($entityClass)) {
-            $entityInstance = app($entityClass);
+        $permissionQuery = EntityPermission::query()
+            ->where($action, '=', true)
+            ->whereIn('role_id', $this->getCurrentUserRoleIds());
+
+        if (!empty($entityClass)) {
+            /** @var Entity $entityInstance */
+            $entityInstance = app()->make($entityClass);
             $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
         }
 
         $hasPermission = $permissionQuery->count() > 0;
-        $this->clean();
 
         return $hasPermission;
     }
 
     /**
-     * The general query filter to remove all entities
-     * that the current user does not have access to.
+     * Limit the given entity query so that the query will only
+     * return items that the user has view permission for.
      */
-    protected function entityRestrictionQuery(Builder $query, string $action): Builder
+    public function restrictEntityQuery(Builder $query): 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;
-    }
-
-    /**
-     * Limited the given entity query so that the query will only
-     * return items that the user has permission for the given ability.
-     */
-    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->getCurrentUserRoles())
-                    ->where('action', '=', $ability)
+        return $query->where(function (Builder $parentQuery) {
+            $parentQuery->whereHas('jointPermissions', function (Builder $permissionQuery) {
+                $permissionQuery->whereIn('role_id', $this->getCurrentUserRoleIds())
                     ->where(function (Builder $query) {
                         $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
                     });
@@ -150,7 +146,7 @@ class PermissionApplicator
      * Extend the given page query to ensure draft items are not visible
      * unless created by the given user.
      */
-    public function enforceDraftVisibilityOnQuery(Builder $query): Builder
+    public function restrictDraftsOnPageQuery(Builder $query): Builder
     {
         return $query->where(function (Builder $query) {
             $query->where('draft', '=', false)
@@ -161,19 +157,6 @@ class PermissionApplicator
         });
     }
 
-    /**
-     * Add restrictions for a generic entity.
-     */
-    public function enforceEntityRestrictions(Entity $entity, Builder $query): Builder
-    {
-        if ($entity instanceof Page) {
-            // Prevent drafts being visible to others.
-            $this->enforceDraftVisibilityOnQuery($query);
-        }
-
-        return $this->entityRestrictionQuery($query, 'view');
-    }
-
     /**
      * Filter items that have entities set as a polymorphic relation.
      * For simplicity, this will not return results attached to draft pages.
@@ -181,18 +164,17 @@ class PermissionApplicator
      *
      * @param Builder|QueryBuilder $query
      */
-    public function filterRestrictedEntityRelations($query, string $tableName, string $entityIdColumn, string $entityTypeColumn, string $action = 'view')
+    public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
     {
         $tableDetails = ['tableName' => $tableName, 'entityIdColumn' => $entityIdColumn, 'entityTypeColumn' => $entityTypeColumn];
         $pageMorphClass = (new Page())->getMorphClass();
 
-        $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails, $action) {
+        $q = $query->whereExists(function ($permissionQuery) use (&$tableDetails) {
             /** @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())
+                ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
                 ->where(function (QueryBuilder $query) {
                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
                 });
@@ -207,51 +189,45 @@ class PermissionApplicator
                 });
         });
 
-        $this->clean();
-
         return $q;
     }
 
     /**
-     * Add conditions to a query to filter the selection to related entities
-     * where view permissions are granted.
+     * Add conditions to a query for a model that's a relation of a page, so only the model results
+     * on visible pages are returned by the query.
+     * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
+     * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
      */
-    public function filterRelatedEntity(string $entityClass, Builder $query, string $tableName, string $entityIdColumn): Builder
+    public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
     {
-        $fullEntityIdColumn = $tableName . '.' . $entityIdColumn;
-        $instance = new $entityClass();
-        $morphClass = $instance->getMorphClass();
+        $fullPageIdColumn = $tableName . '.' . $pageIdColumn;
+        $morphClass = (new Page())->getMorphClass();
 
-        $existsQuery = function ($permissionQuery) use ($fullEntityIdColumn, $morphClass) {
+        $existsQuery = function ($permissionQuery) use ($fullPageIdColumn, $morphClass) {
             /** @var Builder $permissionQuery */
             $permissionQuery->select('joint_permissions.role_id')->from('joint_permissions')
-                ->whereColumn('joint_permissions.entity_id', '=', $fullEntityIdColumn)
+                ->whereColumn('joint_permissions.entity_id', '=', $fullPageIdColumn)
                 ->where('joint_permissions.entity_type', '=', $morphClass)
-                ->where('joint_permissions.action', '=', 'view')
-                ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoles())
+                ->whereIn('joint_permissions.role_id', $this->getCurrentUserRoleIds())
                 ->where(function (QueryBuilder $query) {
                     $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
                 });
         };
 
-        $q = $query->where(function ($query) use ($existsQuery, $fullEntityIdColumn) {
+        $q = $query->where(function ($query) use ($existsQuery, $fullPageIdColumn) {
             $query->whereExists($existsQuery)
-                ->orWhere($fullEntityIdColumn, '=', 0);
+                ->orWhere($fullPageIdColumn, '=', 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();
+        // Prevent visibility of non-owned draft pages
+        $q->whereExists(function (QueryBuilder $query) use ($fullPageIdColumn) {
+            $query->select('id')->from('pages')
+                ->whereColumn('pages.id', '=', $fullPageIdColumn)
+                ->where(function (QueryBuilder $query) {
+                    $query->where('pages.draft', '=', false)
+                        ->orWhere('pages.owned_by', '=', $this->currentUser()->id);
+                });
+        });
 
         return $q;
     }
@@ -273,21 +249,34 @@ class PermissionApplicator
     /**
      * Get the current user.
      */
-    private function currentUser(): User
+    protected function currentUser(): User
     {
-        if (is_null($this->currentUserModel)) {
-            $this->currentUserModel = user();
+        return user();
+    }
+
+    /**
+     * Get the roles for the current logged-in user.
+     *
+     * @return int[]
+     */
+    protected function getCurrentUserRoleIds(): array
+    {
+        if (auth()->guest()) {
+            return [Role::getSystemRole('public')->id];
         }
 
-        return $this->currentUserModel;
+        return $this->currentUser()->roles->pluck('id')->values()->all();
     }
 
     /**
-     * Clean the cached user elements.
+     * Ensure the given action is a valid and expected entity action.
+     * Throws an exception if invalid otherwise does nothing.
+     * @throws InvalidArgumentException
      */
-    private function clean(): void
+    protected function ensureValidEntityAction(string $action): void
     {
-        $this->currentUserModel = null;
-        $this->userRoles = null;
+        if (!in_array($action, EntityPermission::PERMISSIONS)) {
+            throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');
+        }
     }
 }