3 namespace BookStack\Auth\Permissions;
5 use BookStack\Auth\Role;
6 use BookStack\Auth\User;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Entity;
9 use BookStack\Entities\Models\Page;
11 use BookStack\Traits\HasCreatorAndUpdater;
12 use BookStack\Traits\HasOwner;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Query\Builder as QueryBuilder;
15 use Illuminate\Database\Query\JoinClause;
16 use Illuminate\Support\Facades\DB;
17 use InvalidArgumentException;
19 class PermissionApplicator
22 * Checks if an entity has a restriction set upon it.
24 * @param HasCreatorAndUpdater|HasOwner $ownable
26 public function checkOwnableUserAccess(Model $ownable, string $permission): bool
28 $explodedPermission = explode('-', $permission);
29 $action = $explodedPermission[1] ?? $explodedPermission[0];
30 $fullPermission = count($explodedPermission) > 1 ? $permission : $ownable->getMorphClass() . '-' . $permission;
32 $user = $this->currentUser();
33 $userRoleIds = $this->getCurrentUserRoleIds();
35 $allRolePermission = $user->can($fullPermission . '-all');
36 $ownRolePermission = $user->can($fullPermission . '-own');
37 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
38 $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
39 $ownableFieldVal = $ownable->getAttribute($ownerField);
41 if (is_null($ownableFieldVal)) {
42 throw new InvalidArgumentException("{$ownerField} field used but has not been loaded");
45 $isOwner = $user->id === $ownableFieldVal;
46 $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
48 // Handle non entity specific jointPermissions
49 if (in_array($explodedPermission[0], $nonJointPermissions)) {
50 return $hasRolePermission;
53 $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $user->id, $action);
55 return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
59 * Check if there are permissions that are applicable for the given entity item, action and roles.
60 * Returns null when no entity permissions are in force.
62 protected function hasEntityPermission(Entity $entity, array $userRoleIds, int $userId, string $action): ?bool
64 $this->ensureValidEntityAction($action);
66 $adminRoleId = Role::getSystemRole('admin')->id;
67 if (in_array($adminRoleId, $userRoleIds)) {
71 // The array order here is very important due to the fact we walk up the chain
72 // in the flattening loop below. Earlier items in the chain have higher priority.
73 $typeIdList = [$entity->getMorphClass() . ':' . $entity->id];
74 if ($entity instanceof Page && $entity->chapter_id) {
75 $typeIdList[] = 'chapter:' . $entity->chapter_id;
78 if ($entity instanceof Page || $entity instanceof Chapter) {
79 $typeIdList[] = 'book:' . $entity->book_id;
82 $relevantPermissions = EntityPermission::query()
83 ->where(function (Builder $query) use ($typeIdList) {
84 foreach ($typeIdList as $typeId) {
85 $query->orWhere(function (Builder $query) use ($typeId) {
86 [$type, $id] = explode(':', $typeId);
87 $query->where('entity_type', '=', $type)
88 ->where('entity_id', '=', $id);
91 })->where(function (Builder $query) use ($userRoleIds, $userId) {
92 $query->whereIn('role_id', $userRoleIds)
93 ->orWhere('user_id', '=', $userId)
94 ->orWhere(function (Builder $query) {
95 $query->whereNull(['role_id', 'user_id']);
97 })->get(['entity_id', 'entity_type', 'role_id', 'user_id', $action])
100 $permissionMap = new EntityPermissionMap($relevantPermissions);
101 $permitsByType = ['user' => [], 'fallback' => [], 'role' => []];
103 // Collapse and simplify permission structure
104 foreach ($typeIdList as $typeId) {
105 $permissions = $permissionMap->getForEntity($typeId);
106 foreach ($permissions as $permission) {
107 $related = $permission->getAssignedType();
108 $relatedId = $permission->getAssignedTypeId();
109 if (!isset($permitsByType[$related][$relatedId])) {
110 $permitsByType[$related][$relatedId] = $permission->$action;
115 // Return user-level permission if exists
116 if (count($permitsByType['user']) > 0) {
117 return boolval(array_values($permitsByType['user'])[0]);
120 // Return grant or reject from role-level if exists
121 if (count($permitsByType['role']) > 0) {
122 return boolval(max($permitsByType['role']));
125 // Return fallback permission if exists
126 if (count($permitsByType['fallback']) > 0) {
127 return boolval($permitsByType['fallback'][0]);
134 * Checks if a user has the given permission for any items in the system.
135 * Can be passed an entity instance to filter on a specific type.
137 public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
139 $this->ensureValidEntityAction($action);
141 $permissionQuery = EntityPermission::query()
142 ->where($action, '=', true)
143 ->where(function (Builder $query) {
144 $query->whereIn('role_id', $this->getCurrentUserRoleIds())
145 ->orWhere('user_id', '=', $this->currentUser()->id);
148 if (!empty($entityClass)) {
149 /** @var Entity $entityInstance */
150 $entityInstance = app()->make($entityClass);
151 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
154 $hasPermission = $permissionQuery->count() > 0;
156 return $hasPermission;
160 * Limit the given entity query so that the query will only
161 * return items that the user has view permission for.
163 public function restrictEntityQuery(Builder $query, string $morphClass): Builder
165 $this->applyPermissionsToQuery($query, $query->getModel()->getTable(), $morphClass, 'id', '');
171 * @param Builder|QueryBuilder $query
173 protected function applyPermissionsToQuery($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn): void
175 if ($this->currentUser()->hasSystemRole('admin')) {
179 $this->applyFallbackJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
180 $this->applyRoleJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
181 $this->applyUserJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
182 $this->applyPermissionWhereFilter($query, $queryTable, $entityTypeLimiter, $entityTypeColumn);
186 * Apply the where condition to a permission restricting query, to limit based upon the values of the joined
187 * permission data. Query must have joins pre-applied.
188 * Either entityTypeLimiter or entityTypeColumn should be supplied, with the other empty.
189 * Both should not be applied since that would conflict upon intent.
190 * @param Builder|QueryBuilder $query
192 protected function applyPermissionWhereFilter($query, string $queryTable, string $entityTypeLimiter, string $entityTypeColumn)
194 $abilities = ['all' => [], 'own' => []];
195 $types = $entityTypeLimiter ? [$entityTypeLimiter] : ['page', 'chapter', 'bookshelf', 'book'];
196 $fullEntityTypeColumn = $queryTable . '.' . $entityTypeColumn;
197 foreach ($types as $type) {
198 $abilities['all'][$type] = userCan($type . '-view-all');
199 $abilities['own'][$type] = userCan($type . '-view-own');
202 $abilities['all'] = array_filter($abilities['all']);
203 $abilities['own'] = array_filter($abilities['own']);
205 $query->where(function (Builder $query) use ($abilities, $fullEntityTypeColumn, $entityTypeColumn) {
206 $query->where('perms_user', '=', 1)
207 ->orWhere(function (Builder $query) {
208 $query->whereNull('perms_user')->where('perms_role', '=', 1);
209 })->orWhere(function (Builder $query) {
210 $query->whereNull(['perms_user', 'perms_role'])
211 ->where('perms_fallback', '=', 1);
214 if (count($abilities['all']) > 0) {
215 $query->orWhere(function (Builder $query) use ($abilities, $fullEntityTypeColumn, $entityTypeColumn) {
216 $query->whereNull(['perms_user', 'perms_role', 'perms_fallback']);
217 if ($entityTypeColumn) {
218 $query->whereIn($fullEntityTypeColumn, array_keys($abilities['all']));
223 if (count($abilities['own']) > 0) {
224 $query->orWhere(function (Builder $query) use ($abilities, $fullEntityTypeColumn, $entityTypeColumn) {
225 $query->whereNull(['perms_user', 'perms_role', 'perms_fallback'])
226 ->where('owned_by', '=', $this->currentUser()->id);
227 if ($entityTypeColumn) {
228 $query->whereIn($fullEntityTypeColumn, array_keys($abilities['all']));
236 * @param Builder|QueryBuilder $query
238 protected function applyPermissionJoin(callable $joinCallable, string $subAlias, $query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
240 $joinCondition = $this->getJoinCondition($queryTable, $subAlias, $entityIdColumn, $entityTypeColumn);
242 $query->joinSub(function (QueryBuilder $joinQuery) use ($joinCallable, $entityTypeLimiter) {
243 $joinQuery->select(['entity_id', 'entity_type'])->from('entity_permissions_collapsed')
244 ->groupBy('entity_id', 'entity_type');
245 $joinCallable($joinQuery);
247 if ($entityTypeLimiter) {
248 $joinQuery->where('entity_type', '=', $entityTypeLimiter);
250 }, $subAlias, $joinCondition, null, null, 'left');
254 * @param Builder|QueryBuilder $query
256 protected function applyUserJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
258 $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
259 $joinQuery->selectRaw('max(view) as perms_user')
260 ->where('user_id', '=', $this->currentUser()->id);
261 }, 'p_u', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
266 * @param Builder|QueryBuilder $query
268 protected function applyRoleJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
270 $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
271 $joinQuery->selectRaw('max(view) as perms_role')
272 ->whereIn('role_id', $this->getCurrentUserRoleIds());
273 }, 'p_r', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
277 * @param Builder|QueryBuilder $query
279 protected function applyFallbackJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
281 $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
282 $joinQuery->selectRaw('max(view) as perms_fallback')
283 ->whereNull(['role_id', 'user_id']);
284 }, 'p_f', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
287 protected function getJoinCondition(string $queryTable, string $joinTableName, string $entityIdColumn, string $entityTypeColumn): callable
289 return function (JoinClause $join) use ($queryTable, $joinTableName, $entityIdColumn, $entityTypeColumn) {
290 $join->on($queryTable . '.' . $entityIdColumn, '=', $joinTableName . '.entity_id');
291 if ($entityTypeColumn) {
292 $join->on($queryTable . '.' . $entityTypeColumn, '=', $joinTableName . '.entity_type');
298 * Extend the given page query to ensure draft items are not visible
299 * unless created by the given user.
301 public function restrictDraftsOnPageQuery(Builder $query): Builder
303 return $query->where(function (Builder $query) {
304 $query->where('draft', '=', false)
305 ->orWhere(function (Builder $query) {
306 $query->where('draft', '=', true)
307 ->where('owned_by', '=', $this->currentUser()->id);
313 * Filter items that have entities set as a polymorphic relation.
314 * For simplicity, this will not return results attached to draft pages.
315 * Draft pages should never really have related items though.
317 * @param Builder|QueryBuilder $query
319 public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
321 $query->leftJoinSub(function (QueryBuilder $query) {
322 $query->select(['id as entity_id', DB::raw("'page' as entity_type"), 'owned_by', 'deleted_at', 'draft'])->from('pages');
323 $tablesByType = ['page' => 'pages', 'book' => 'books', 'chapter' => 'chapters', 'bookshelf' => 'bookshelves'];
324 foreach ($tablesByType as $type => $table) {
325 $query->unionAll(function (QueryBuilder $query) use ($type, $table) {
326 $query->select(['id as entity_id', DB::raw("'{$type}' as entity_type"), 'owned_by', 'deleted_at', DB::raw('0 as draft')])->from($table);
329 }, 'entities', function (JoinClause $join) use ($tableName, $entityIdColumn, $entityTypeColumn) {
330 $join->on($tableName . '.' . $entityIdColumn, '=', 'entities.entity_id')
331 ->on($tableName . '.' . $entityTypeColumn, '=', 'entities.entity_type');
334 $this->applyPermissionsToQuery($query, $tableName, '', $entityIdColumn, $entityTypeColumn);
335 // TODO - Test page draft access (Might allow drafts which should not be seen)
341 * Add conditions to a query for a model that's a relation of a page, so only the model results
342 * on visible pages are returned by the query.
343 * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
344 * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
346 public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
348 $morphClass = (new Page())->getMorphClass();
350 $this->applyPermissionsToQuery($query, $tableName, $morphClass, $pageIdColumn, '');
351 // TODO - Draft display
352 // TODO - Likely need owned_by entity join workaround as used above
357 * Get the current user.
359 protected function currentUser(): User
365 * Get the roles for the current logged-in user.
369 protected function getCurrentUserRoleIds(): array
371 if (auth()->guest()) {
372 return [Role::getSystemRole('public')->id];
375 return $this->currentUser()->roles->pluck('id')->values()->all();
379 * Ensure the given action is a valid and expected entity action.
380 * Throws an exception if invalid otherwise does nothing.
381 * @throws InvalidArgumentException
383 protected function ensureValidEntityAction(string $action): void
385 if (!in_array($action, EntityPermission::PERMISSIONS)) {
386 throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');