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;
use BookStack\Traits\HasOwner;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder;
+use Illuminate\Database\Query\JoinClause;
+use Illuminate\Support\Facades\DB;
+use InvalidArgumentException;
class PermissionApplicator
{
/**
- * @var ?array<int>
+ * Checks if an entity has a restriction set upon it.
+ *
+ * @param HasCreatorAndUpdater|HasOwner $ownable
*/
- protected $userRoles = null;
+ public function checkOwnableUserAccess(Model $ownable, string $permission): bool
+ {
+ $explodedPermission = explode('-', $permission);
+ $action = $explodedPermission[1] ?? $explodedPermission[0];
+ $fullPermission = count($explodedPermission) > 1 ? $permission : $ownable->getMorphClass() . '-' . $permission;
- /**
- * @var ?User
- */
- protected $currentUserModel = null;
+ $user = $this->currentUser();
+ $userRoleIds = $this->getCurrentUserRoleIds();
- /**
- * Get the roles for the current logged in user.
- */
- protected function getCurrentUserRoles(): array
- {
- if (!is_null($this->userRoles)) {
- return $this->userRoles;
+ $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");
}
- if (auth()->guest()) {
- $this->userRoles = [Role::getSystemRole('public')->id];
- } else {
- $this->userRoles = $this->currentUser()->roles->pluck('id')->values()->all();
+ $isOwner = $user->id === $ownableFieldVal;
+ $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
+
+ // Handle non entity specific jointPermissions
+ if (in_array($explodedPermission[0], $nonJointPermissions)) {
+ return $hasRolePermission;
}
- return $this->userRoles;
+ $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $user->id, $action);
+
+ return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
}
/**
- * Checks if an entity has a restriction set upon it.
- *
- * @param HasCreatorAndUpdater|HasOwner $ownable
+ * 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.
*/
- public function checkOwnableUserAccess(Model $ownable, string $permission): bool
+ protected function hasEntityPermission(Entity $entity, array $userRoleIds, int $userId, string $action): ?bool
{
- $explodedPermission = explode('-', $permission);
+ $this->ensureValidEntityAction($action);
- $baseQuery = $ownable->newQuery()->where('id', '=', $ownable->id);
- $action = end($explodedPermission);
- $user = $this->currentUser();
+ $adminRoleId = Role::getSystemRole('admin')->id;
+ if (in_array($adminRoleId, $userRoleIds)) {
+ return true;
+ }
- $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
+ // The array order here is very important due to the fact we walk up the chain
+ // in the flattening loop below. Earlier items in the chain have higher priority.
+ $typeIdList = [$entity->getMorphClass() . ':' . $entity->id];
+ if ($entity instanceof Page && $entity->chapter_id) {
+ $typeIdList[] = 'chapter:' . $entity->chapter_id;
+ }
- // 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;
+ if ($entity instanceof Page || $entity instanceof Chapter) {
+ $typeIdList[] = 'book:' . $entity->book_id;
+ }
+
+ $relevantPermissions = EntityPermission::query()
+ ->where(function (Builder $query) use ($typeIdList) {
+ foreach ($typeIdList as $typeId) {
+ $query->orWhere(function (Builder $query) use ($typeId) {
+ [$type, $id] = explode(':', $typeId);
+ $query->where('entity_type', '=', $type)
+ ->where('entity_id', '=', $id);
+ });
+ }
+ })->where(function (Builder $query) use ($userRoleIds, $userId) {
+ $query->whereIn('role_id', $userRoleIds)
+ ->orWhere('user_id', '=', $userId)
+ ->orWhere(function (Builder $query) {
+ $query->whereNull(['role_id', 'user_id']);
+ });
+ })->get(['entity_id', 'entity_type', 'role_id', 'user_id', $action])
+ ->all();
+
+ $permissionMap = new EntityPermissionMap($relevantPermissions);
+ $permitsByType = ['user' => [], 'fallback' => [], 'role' => []];
+
+ // Collapse and simplify permission structure
+ foreach ($typeIdList as $typeId) {
+ $permissions = $permissionMap->getForEntity($typeId);
+ foreach ($permissions as $permission) {
+ $related = $permission->getAssignedType();
+ $relatedId = $permission->getAssignedTypeId();
+ if (!isset($permitsByType[$related][$relatedId])) {
+ $permitsByType[$related][$relatedId] = $permission->$action;
+ }
+ }
+ }
- return $allPermission || ($isOwner && $ownPermission);
+ // Return user-level permission if exists
+ if (count($permitsByType['user']) > 0) {
+ return boolval(array_values($permitsByType['user'])[0]);
}
- // Handle abnormal create jointPermissions
- if ($action === 'create') {
- $action = $permission;
+ // Return grant or reject from role-level if exists
+ if (count($permitsByType['role']) > 0) {
+ return boolval(max($permitsByType['role']));
}
- $hasAccess = $this->entityRestrictionQuery($baseQuery, $action)->count() > 0;
- $this->clean();
+ // Return fallback permission if exists
+ if (count($permitsByType['fallback']) > 0) {
+ return boolval($permitsByType['fallback'][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);
+
+ $permissionQuery = EntityPermission::query()
+ ->where($action, '=', true)
+ ->where(function (Builder $query) {
+ $query->whereIn('role_id', $this->getCurrentUserRoleIds())
+ ->orWhere('user_id', '=', $this->currentUser()->id);
});
- if (!is_null($entityClass)) {
- $entityInstance = app($entityClass);
+ 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, string $morphClass): 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->applyPermissionsToQuery($query, $query->getModel()->getTable(), $morphClass, 'id', '');
- $this->clean();
+ return $query;
+ }
- return $q;
+ /**
+ * @param Builder|QueryBuilder $query
+ */
+ protected function applyPermissionsToQuery($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn): void
+ {
+ if ($this->currentUser()->hasSystemRole('admin')) {
+ return;
+ }
+
+ $this->applyFallbackJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
+ $this->applyRoleJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
+ $this->applyUserJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
+ $this->applyPermissionWhereFilter($query, $queryTable, $entityTypeLimiter, $entityTypeColumn);
}
/**
- * Limited the given entity query so that the query will only
- * return items that the user has permission for the given ability.
+ * Apply the where condition to a permission restricting query, to limit based upon the values of the joined
+ * permission data. Query must have joins pre-applied.
+ * Either entityTypeLimiter or entityTypeColumn should be supplied, with the other empty.
+ * Both should not be applied since that would conflict upon intent.
+ * @param Builder|QueryBuilder $query
*/
- public function restrictEntityQuery(Builder $query, string $ability = 'view'): Builder
+ protected function applyPermissionWhereFilter($query, string $queryTable, string $entityTypeLimiter, string $entityTypeColumn)
{
- $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)
- ->where(function (Builder $query) {
- $this->addJointHasPermissionCheck($query, $this->currentUser()->id);
- });
- });
+ $abilities = ['all' => [], 'own' => []];
+ $types = $entityTypeLimiter ? [$entityTypeLimiter] : ['page', 'chapter', 'bookshelf', 'book'];
+ $fullEntityTypeColumn = $queryTable . '.' . $entityTypeColumn;
+ foreach ($types as $type) {
+ $abilities['all'][$type] = userCan($type . '-view-all');
+ $abilities['own'][$type] = userCan($type . '-view-own');
+ }
+
+ $abilities['all'] = array_filter($abilities['all']);
+ $abilities['own'] = array_filter($abilities['own']);
+
+ $query->where(function (Builder $query) use ($abilities, $fullEntityTypeColumn, $entityTypeColumn) {
+ $query->where('perms_user', '=', 1)
+ ->orWhere(function (Builder $query) {
+ $query->whereNull('perms_user')->where('perms_role', '=', 1);
+ })->orWhere(function (Builder $query) {
+ $query->whereNull(['perms_user', 'perms_role'])
+ ->where('perms_fallback', '=', 1);
+ });
+
+ if (count($abilities['all']) > 0) {
+ $query->orWhere(function (Builder $query) use ($abilities, $fullEntityTypeColumn, $entityTypeColumn) {
+ $query->whereNull(['perms_user', 'perms_role', 'perms_fallback']);
+ if ($entityTypeColumn) {
+ $query->whereIn($fullEntityTypeColumn, array_keys($abilities['all']));
+ }
+ });
+ }
+
+ if (count($abilities['own']) > 0) {
+ $query->orWhere(function (Builder $query) use ($abilities, $fullEntityTypeColumn, $entityTypeColumn) {
+ $query->whereNull(['perms_user', 'perms_role', 'perms_fallback'])
+ ->where('owned_by', '=', $this->currentUser()->id);
+ if ($entityTypeColumn) {
+ $query->whereIn($fullEntityTypeColumn, array_keys($abilities['all']));
+ }
+ });
+ }
});
}
+ /**
+ * @param Builder|QueryBuilder $query
+ */
+ protected function applyPermissionJoin(callable $joinCallable, string $subAlias, $query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
+ {
+ $joinCondition = $this->getJoinCondition($queryTable, $subAlias, $entityIdColumn, $entityTypeColumn);
+
+ $query->joinSub(function (QueryBuilder $joinQuery) use ($joinCallable, $entityTypeLimiter) {
+ $joinQuery->select(['entity_id', 'entity_type'])->from('entity_permissions_collapsed')
+ ->groupBy('entity_id', 'entity_type');
+ $joinCallable($joinQuery);
+
+ if ($entityTypeLimiter) {
+ $joinQuery->where('entity_type', '=', $entityTypeLimiter);
+ }
+ }, $subAlias, $joinCondition, null, null, 'left');
+ }
+
+ /**
+ * @param Builder|QueryBuilder $query
+ */
+ protected function applyUserJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
+ {
+ $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
+ $joinQuery->selectRaw('max(view) as perms_user')
+ ->where('user_id', '=', $this->currentUser()->id);
+ }, 'p_u', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
+ }
+
+
+ /**
+ * @param Builder|QueryBuilder $query
+ */
+ protected function applyRoleJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
+ {
+ $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
+ $joinQuery->selectRaw('max(view) as perms_role')
+ ->whereIn('role_id', $this->getCurrentUserRoleIds());
+ }, 'p_r', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
+ }
+
+ /**
+ * @param Builder|QueryBuilder $query
+ */
+ protected function applyFallbackJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
+ {
+ $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
+ $joinQuery->selectRaw('max(view) as perms_fallback')
+ ->whereNull(['role_id', 'user_id']);
+ }, 'p_f', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
+ }
+
+ protected function getJoinCondition(string $queryTable, string $joinTableName, string $entityIdColumn, string $entityTypeColumn): callable
+ {
+ return function (JoinClause $join) use ($queryTable, $joinTableName, $entityIdColumn, $entityTypeColumn) {
+ $join->on($queryTable . '.' . $entityIdColumn, '=', $joinTableName . '.entity_id');
+ if ($entityTypeColumn) {
+ $join->on($queryTable . '.' . $entityTypeColumn, '=', $joinTableName . '.entity_type');
+ }
+ };
+ }
+
/**
* 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)
});
}
- /**
- * Add restrictions for a generic entity.
- */
- public function enforceEntityRestrictions(Entity $entity, Builder $query, string $action = 'view'): Builder
- {
- if ($entity instanceof Page) {
- // Prevent drafts being visible to others.
- $this->enforceDraftVisibilityOnQuery($query);
- }
-
- return $this->entityRestrictionQuery($query, $action);
- }
-
/**
* Filter items that have entities set as a polymorphic relation.
* For simplicity, this will not return results attached to draft pages.
*
* @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) {
- /** @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);
+ $query->leftJoinSub(function (QueryBuilder $query) {
+ $query->select(['id as entity_id', DB::raw("'page' as entity_type"), 'owned_by', 'deleted_at', 'draft'])->from('pages');
+ $tablesByType = ['page' => 'pages', 'book' => 'books', 'chapter' => 'chapters', 'bookshelf' => 'bookshelves'];
+ foreach ($tablesByType as $type => $table) {
+ $query->unionAll(function (QueryBuilder $query) use ($type, $table) {
+ $query->select(['id as entity_id', DB::raw("'{$type}' as entity_type"), 'owned_by', 'deleted_at', DB::raw('0 as draft')])->from($table);
});
+ }
+ }, 'entities', function (JoinClause $join) use ($tableName, $entityIdColumn, $entityTypeColumn) {
+ $join->on($tableName . '.' . $entityIdColumn, '=', 'entities.entity_id')
+ ->on($tableName . '.' . $entityTypeColumn, '=', 'entities.entity_type');
});
- $this->clean();
+ $this->applyPermissionsToQuery($query, $tableName, '', $entityIdColumn, $entityTypeColumn);
+ // TODO - Test page draft access (Might allow drafts which should not be seen)
- return $q;
+ return $query;
}
/**
- * 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();
-
- $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);
- });
- };
+ $morphClass = (new Page())->getMorphClass();
- $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;
+ $this->applyPermissionsToQuery($query, $tableName, $morphClass, $pageIdColumn, '');
+ // TODO - Draft display
+ // TODO - Likely need owned_by entity join workaround as used above
+ return $query;
}
/**
- * Add the query for checking the given user id has permission
- * within the join_permissions table.
- *
- * @param QueryBuilder|Builder $query
+ * Get the current user.
*/
- protected function addJointHasPermissionCheck($query, int $userIdToCheck)
+ protected function currentUser(): User
{
- $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);
- });
+ return user();
}
/**
- * Get the current user.
+ * Get the roles for the current logged-in user.
+ *
+ * @return int[]
*/
- private function currentUser(): User
+ protected function getCurrentUserRoleIds(): array
{
- if (is_null($this->currentUserModel)) {
- $this->currentUserModel = user();
+ 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');
+ }
}
}