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 InvalidArgumentException;
18 class PermissionApplicator
21 * Checks if an entity has a restriction set upon it.
23 * @param HasCreatorAndUpdater|HasOwner $ownable
25 public function checkOwnableUserAccess(Model $ownable, string $permission): bool
27 $explodedPermission = explode('-', $permission);
28 $action = $explodedPermission[1] ?? $explodedPermission[0];
29 $fullPermission = count($explodedPermission) > 1 ? $permission : $ownable->getMorphClass() . '-' . $permission;
31 $user = $this->currentUser();
32 $userRoleIds = $this->getCurrentUserRoleIds();
34 $allRolePermission = $user->can($fullPermission . '-all');
35 $ownRolePermission = $user->can($fullPermission . '-own');
36 $nonJointPermissions = ['restrictions', 'image', 'attachment', 'comment'];
37 $ownerField = ($ownable instanceof Entity) ? 'owned_by' : 'created_by';
38 $ownableFieldVal = $ownable->getAttribute($ownerField);
40 if (is_null($ownableFieldVal)) {
41 throw new InvalidArgumentException("{$ownerField} field used but has not been loaded");
44 $isOwner = $user->id === $ownableFieldVal;
45 $hasRolePermission = $allRolePermission || ($isOwner && $ownRolePermission);
47 // Handle non entity specific jointPermissions
48 if (in_array($explodedPermission[0], $nonJointPermissions)) {
49 return $hasRolePermission;
52 $hasApplicableEntityPermissions = $this->hasEntityPermission($ownable, $userRoleIds, $user->id, $action);
54 return is_null($hasApplicableEntityPermissions) ? $hasRolePermission : $hasApplicableEntityPermissions;
58 * Check if there are permissions that are applicable for the given entity item, action and roles.
59 * Returns null when no entity permissions are in force.
61 protected function hasEntityPermission(Entity $entity, array $userRoleIds, int $userId, string $action): ?bool
63 $this->ensureValidEntityAction($action);
65 $adminRoleId = Role::getSystemRole('admin')->id;
66 if (in_array($adminRoleId, $userRoleIds)) {
70 // The array order here is very important due to the fact we walk up the chain
71 // in the flattening loop below. Earlier items in the chain have higher priority.
72 $typeIdList = [$entity->getMorphClass() . ':' . $entity->id];
73 if ($entity instanceof Page && $entity->chapter_id) {
74 $typeIdList[] = 'chapter:' . $entity->chapter_id;
77 if ($entity instanceof Page || $entity instanceof Chapter) {
78 $typeIdList[] = 'book:' . $entity->book_id;
81 $relevantPermissions = EntityPermission::query()
82 ->where(function (Builder $query) use ($typeIdList) {
83 foreach ($typeIdList as $typeId) {
84 $query->orWhere(function (Builder $query) use ($typeId) {
85 [$type, $id] = explode(':', $typeId);
86 $query->where('entity_type', '=', $type)
87 ->where('entity_id', '=', $id);
90 })->where(function (Builder $query) use ($userRoleIds, $userId) {
91 $query->whereIn('role_id', $userRoleIds)
92 ->orWhere('user_id', '=', $userId)
93 ->orWhere(function (Builder $query) {
94 $query->whereNull(['role_id', 'user_id']);
96 })->get(['entity_id', 'entity_type', 'role_id', 'user_id', $action])
99 $permissionMap = new EntityPermissionMap($relevantPermissions);
100 $permitsByType = ['user' => [], 'fallback' => [], 'role' => []];
102 // Collapse and simplify permission structure
103 foreach ($typeIdList as $typeId) {
104 $permissions = $permissionMap->getForEntity($typeId);
105 foreach ($permissions as $permission) {
106 $related = $permission->getAssignedType();
107 $relatedId = $permission->getAssignedTypeId();
108 if (!isset($permitsByType[$related][$relatedId])) {
109 $permitsByType[$related][$relatedId] = $permission->$action;
114 // Return user-level permission if exists
115 if (count($permitsByType['user']) > 0) {
116 return boolval(array_values($permitsByType['user'])[0]);
119 // Return grant or reject from role-level if exists
120 if (count($permitsByType['role']) > 0) {
121 return boolval(max($permitsByType['role']));
124 // Return fallback permission if exists
125 if (count($permitsByType['fallback']) > 0) {
126 return boolval($permitsByType['fallback'][0]);
133 * Checks if a user has the given permission for any items in the system.
134 * Can be passed an entity instance to filter on a specific type.
136 public function checkUserHasEntityPermissionOnAny(string $action, string $entityClass = ''): bool
138 $this->ensureValidEntityAction($action);
140 $permissionQuery = EntityPermission::query()
141 ->where($action, '=', true)
142 ->where(function (Builder $query) {
143 $query->whereIn('role_id', $this->getCurrentUserRoleIds())
144 ->orWhere('user_id', '=', $this->currentUser()->id);
147 if (!empty($entityClass)) {
148 /** @var Entity $entityInstance */
149 $entityInstance = app()->make($entityClass);
150 $permissionQuery = $permissionQuery->where('entity_type', '=', $entityInstance->getMorphClass());
153 $hasPermission = $permissionQuery->count() > 0;
155 return $hasPermission;
159 * Limit the given entity query so that the query will only
160 * return items that the user has view permission for.
162 public function restrictEntityQuery(Builder $query, string $morphClass): Builder
164 $this->applyPermissionsToQuery($query, $query->getModel()->getTable(), $morphClass, 'id', '');
170 * @param Builder|QueryBuilder $query
172 protected function applyPermissionsToQuery($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn): void
174 if ($this->currentUser()->hasSystemRole('admin')) {
178 $this->applyFallbackJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
179 $this->applyRoleJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
180 $this->applyUserJoin($query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
181 $this->applyPermissionWhereFilter($query, $queryTable, $entityTypeLimiter, $entityTypeColumn);
185 * Apply the where condition to a permission restricting query, to limit based upon the values of the joined
186 * permission data. Query must have joins pre-applied.
187 * Either entityTypeLimiter or entityTypeColumn should be supplied, with the other empty.
188 * Both should not be applied since that would conflict upon intent.
189 * @param Builder|QueryBuilder $query
191 protected function applyPermissionWhereFilter($query, string $queryTable, string $entityTypeLimiter, string $entityTypeColumn)
193 $abilities = ['all' => [], 'own' => []];
194 $types = $entityTypeLimiter ? [$entityTypeLimiter] : ['page', 'chapter', 'bookshelf', 'book'];
195 $fullEntityTypeColumn = $queryTable . '.' . $entityTypeColumn;
196 foreach ($types as $type) {
197 $abilities['all'][$type] = userCan($type . '-view-all');
198 $abilities['own'][$type] = userCan($type . '-view-own');
201 $abilities['all'] = array_filter($abilities['all']);
202 $abilities['own'] = array_filter($abilities['own']);
204 $query->where(function (Builder $query) use ($abilities, $fullEntityTypeColumn) {
205 $query->where('perms_user', '=', 1)
206 ->orWhere(function (Builder $query) {
207 $query->whereNull('perms_user')->where('perms_role', '=', 1);
208 })->orWhere(function (Builder $query) {
209 $query->whereNull(['perms_user', 'perms_role'])
210 ->where('perms_fallback', '=', 1);
213 if (count($abilities['all']) > 0) {
214 $query->orWhere(function (Builder $query) use ($abilities, $fullEntityTypeColumn) {
215 $query->whereNull(['perms_user', 'perms_role', 'perms_fallback']);
216 if ($fullEntityTypeColumn) {
217 $query->whereIn($fullEntityTypeColumn, array_keys($abilities['all']));
222 if (count($abilities['own']) > 0) {
223 $query->orWhere(function (Builder $query) use ($abilities, $fullEntityTypeColumn) {
224 $query->whereNull(['perms_user', 'perms_role', 'perms_fallback'])
225 ->where('owned_by', '=', $this->currentUser()->id);
226 if ($fullEntityTypeColumn) {
227 $query->whereIn($fullEntityTypeColumn, array_keys($abilities['all']));
235 * @param Builder|QueryBuilder $query
237 protected function applyPermissionJoin(callable $joinCallable, string $subAlias, $query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
239 $joinCondition = $this->getJoinCondition($queryTable, $subAlias, $entityIdColumn, $entityTypeColumn);
241 $query->joinSub(function (QueryBuilder $joinQuery) use ($joinCallable, $entityTypeLimiter) {
242 $joinQuery->select(['entity_id', 'entity_type'])->from('entity_permissions_collapsed')
243 ->groupBy('entity_id', 'entity_type');
244 $joinCallable($joinQuery);
246 if ($entityTypeLimiter) {
247 $joinQuery->where('entity_type', '=', $entityTypeLimiter);
249 }, $subAlias, $joinCondition, null, null, 'left');
253 * @param Builder|QueryBuilder $query
255 protected function applyUserJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
257 $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
258 $joinQuery->selectRaw('max(view) as perms_user')
259 ->where('user_id', '=', $this->currentUser()->id);
260 }, 'p_u', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
265 * @param Builder|QueryBuilder $query
267 protected function applyRoleJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
269 $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
270 $joinQuery->selectRaw('max(view) as perms_role')
271 ->whereIn('role_id', $this->getCurrentUserRoleIds());
272 }, 'p_r', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
276 * @param Builder|QueryBuilder $query
278 protected function applyFallbackJoin($query, string $queryTable, string $entityTypeLimiter, string $entityIdColumn, string $entityTypeColumn)
280 $this->applyPermissionJoin(function (QueryBuilder $joinQuery) {
281 $joinQuery->selectRaw('max(view) as perms_fallback')
282 ->whereNull(['role_id', 'user_id']);
283 }, 'p_f', $query, $queryTable, $entityTypeLimiter, $entityIdColumn, $entityTypeColumn);
286 protected function getJoinCondition(string $queryTable, string $joinTableName, string $entityIdColumn, string $entityTypeColumn): callable
288 return function (JoinClause $join) use ($queryTable, $joinTableName, $entityIdColumn, $entityTypeColumn) {
289 $join->on($queryTable . '.' . $entityIdColumn, '=', $joinTableName . '.entity_id');
290 if ($entityTypeColumn) {
291 $join->on($queryTable . '.' . $entityTypeColumn, '=', $joinTableName . '.entity_type');
297 * Extend the given page query to ensure draft items are not visible
298 * unless created by the given user.
300 public function restrictDraftsOnPageQuery(Builder $query): Builder
302 return $query->where(function (Builder $query) {
303 $query->where('draft', '=', false)
304 ->orWhere(function (Builder $query) {
305 $query->where('draft', '=', true)
306 ->where('owned_by', '=', $this->currentUser()->id);
312 * Filter items that have entities set as a polymorphic relation.
313 * For simplicity, this will not return results attached to draft pages.
314 * Draft pages should never really have related items though.
316 * @param Builder|QueryBuilder $query
318 public function restrictEntityRelationQuery($query, string $tableName, string $entityIdColumn, string $entityTypeColumn)
320 $this->applyPermissionsToQuery($query, $tableName, '', $entityIdColumn, $entityTypeColumn);
321 // TODO - Test page draft access (Might allow drafts which should not be seen)
327 * Add conditions to a query for a model that's a relation of a page, so only the model results
328 * on visible pages are returned by the query.
329 * Is effectively the same as "restrictEntityRelationQuery" but takes into account page drafts
330 * while not expecting a polymorphic relation, Just a simpler one-page-to-many-relations set-up.
332 public function restrictPageRelationQuery(Builder $query, string $tableName, string $pageIdColumn): Builder
334 $morphClass = (new Page())->getMorphClass();
336 $this->applyPermissionsToQuery($query, $tableName, $morphClass, $pageIdColumn, '');
337 // TODO - Draft display
342 * Get the current user.
344 protected function currentUser(): User
350 * Get the roles for the current logged-in user.
354 protected function getCurrentUserRoleIds(): array
356 if (auth()->guest()) {
357 return [Role::getSystemRole('public')->id];
360 return $this->currentUser()->roles->pluck('id')->values()->all();
364 * Ensure the given action is a valid and expected entity action.
365 * Throws an exception if invalid otherwise does nothing.
366 * @throws InvalidArgumentException
368 protected function ensureValidEntityAction(string $action): void
370 if (!in_array($action, EntityPermission::PERMISSIONS)) {
371 throw new InvalidArgumentException('Action should be a simple entity permission action, not a role permission');